Monday, April 18, 2011

rename file if already exists in database while uploading

I like to use the the way windows allows for unique file or folders: New Folder --> New Folder (2) if the folder exists.
string fileName = /* your file path */
string newFileName = fileName;
int count = 2;
while (System.IO.File.Exists(newFileName))
{
    if(fileName.EndsWith("\\")) fileName = fileName.Remove(fileName.Length-1);

    string dir = fileName.Substring(0,fileName.LastIndexOf("\\"));
    string fName = fileName.Replace(dir, "");
    string name = fName.Split('.')[0];
    string ext = fName.Split('.')[1];
    newFileName = dir + string.Format("{0} ({1}).{2}", name, count.ToString(), ext);
    count++;
}
// Here you would use your unique newFileName
I hope I understood you correctly

1 comment:

  1. // Authenticate here as we need Session and Request objects to be initialised
    protected void Application_PreRequestHandlerExecute(Object sender, EventArgs e)
    {

    //HttpApplication app = sender as HttpApplication;
    //string acceptEncoding = app.Request.Headers["Accept-Encoding"];
    //System.IO.Stream prevUncompressedStream = app.Response.Filter;
    //if (!(app.Context.CurrentHandler is Page || app.Context.CurrentHandler.IsReusable.GetType().Name == "SyncSessionlessHandler") || app.Request["HTTP_X_MICROSOFTAJAX"] != null)
    //{
    // return;
    //}
    //if (acceptEncoding == null || acceptEncoding.Length == 0)
    //{
    // return;
    //}
    //acceptEncoding = acceptEncoding.ToLower();
    //if (acceptEncoding.Contains("deflate") || acceptEncoding == "*")
    //{
    // // defalte
    // app.Response.Filter = new System.IO.Compression.DeflateStream(prevUncompressedStream, System.IO.Compression.CompressionMode.Compress);
    // app.Response.AppendHeader("Content-Encoding", "deflate");
    //}
    //else if (acceptEncoding.Contains("gzip"))
    //{
    // // gzip
    // app.Response.Filter = new System.IO.Compression.GZipStream(prevUncompressedStream, System.IO.Compression.CompressionMode.Compress);
    // app.Response.AppendHeader("Content-Encoding", "gzip");
    //}

    }

    ReplyDelete