Hi all..
I'm having a little trouble with an upload of a file..
i use asp.net with C# language..
I want to add datetime in the name of the file so that when a user uploads a file such as "test.doc" it would be saved into the server as "test-20101123-0533-milisecond.doc" and stored in the database as in a field as Uploads/test-20101123-0533-milisecond.doc

"can u help me, please?"

Dani AI

Generated

Good start by — splitting name and extension and appending a timestamp is the right idea. For a more robust, production-ready approach: sanitize the original name (remove invalid filename chars), use a predictable timestamp format (for example yyyyMMdd-HHmmss-fff to include milliseconds), create the uploads folder if it does not exist, and validate file type/size before saving. Prefer UTC (DateTime.UtcNow) for server-generated timestamps when files may be shared across time zones.

Here is a concise helper you can adapt (WebForms example). Pass virtualFolder like "~/Uploads".

using System;
using System.IO;
using System.Linq;
using System.Web;

public static string SaveUploadWithTimestamp(System.Web.UI.WebControls.FileUpload upload, string virtualFolder)
{
    if (upload == null || !upload.HasFile) return null;
    var name = Path.GetFileNameWithoutExtension(upload.FileName);
    var ext = Path.GetExtension(upload.FileName);
    var safe = new string(name.Where(c => !Path.GetInvalidFileNameChars().Contains(c)).ToArray()).Trim();
    if (string.IsNullOrEmpty(safe)) safe = "file";
    var ts = DateTime.UtcNow.ToString("yyyyMMdd-HHmmss-fff");
    var newName = safe + "-" + ts + ext;
    var physical = HttpContext.Current.Server.MapPath(virtualFolder);
    Directory.CreateDirectory(physical);
    var full = Path.Combine(physical, newName);
    upload.SaveAs(full);
    var virtualPath = virtualFolder.TrimEnd('/') + "/" + newName;
    return virtualPath.TrimStart('~','/');
}

Troubleshooting notes: ensure the app pool has write permission on the uploads folder; enforce a whitelist of allowed extensions and a max file size; catch and log exceptions around SaveAs; timestamp+milliseconds usually avoids collisions, but add a short GUID suffix if you expect many concurrent uploads; store the virtual path in the database (e.g., Uploads/your-file-...) rather than a physical server path.

Recommended Answers

All 5 Replies

Hi,heres some sample code that i hope will help you,basically whats happening with this code is that we retrieve,the FileName from an Upload Control then we separate the fileName & Extension,what youb then do is build up the file Name with fileName+DateTime+Extension,then we save the file on the specied server path,this is not complicated code its just show the basics,if you have futher question feel free to post them...

protected void btnSave_Click(object sender, EventArgs e)
        {
            if (this.FileUpload1.HasFile)
            {
          
                string strFileName = FileUpload1.FileName.ToString();
                string strExtension = Path.GetExtension(strFileName);
                string strTimeStamp = DateTime.Now.Date.ToString();
                strTimeStamp = strTimeStamp.Replace("/", "-");
                strTimeStamp = strTimeStamp.Replace(" ", "-");
                strTimeStamp = strTimeStamp.Replace(":", "-");
                string strName = Path.GetFileNameWithoutExtension(strFileName);
                strFileName = strName + "-" + strTimeStamp + strExtension;
                txtName.Text = strTimeStamp;
                this.FileUpload1.SaveAs(Server.MapPath(@"~\Uploads\" + strFileName.ToString()));
            }
            else
            {
               
            }
        }

Sorry forgot this part. Note that the above code is part of the IO class so you need to put the following on top.

using System.IO;

to samacoba.. thank you very much..
very helpful.. :)

Heres the Refined Code

if (this.FileUpload1.HasFile)
            {
          
                string strFileName = FileUpload1.FileName.ToString();
                string strName = Path.GetFileNameWithoutExtension(strFileName);
                string strTimeStamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                string strExtension = Path.GetExtension(strFileName);
                strTimeStamp = strTimeStamp.Replace(":","");
                strTimeStamp = strTimeStamp.Replace("-","");
                strTimeStamp = strTimeStamp.Replace(" ","");
                strTimeStamp = strTimeStamp.Insert(8,"-");
                strTimeStamp = strTimeStamp.Insert(13, "-");
                strFileName = strName + "-" + strTimeStamp + strExtension;
                txtName.Text = strFileName;
                this.FileUpload1.SaveAs(Server.MapPath(@"~\Uploads\" + strFileName.ToString()));
            }
            else
            {
                ////MessageBox Logic
            }

thx for this.. very helpful.. ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.