Search code examples
c#asp.netmemorystream

Is there a way to rename the uploaded file without saving it?


I tried looking into other solutions, however they suggest either:

  1. to save the file with a different name with saveAs()
  2. to change the file name once the file is saved with Move() or Copy()

In my case I need to rename it without saving it. I tried changing the file.FileName property, however it is ReadOnly.

The result I'm trying to get is:

public HttpPostedFileBase renameFiles(HttpPostedFileBase file)
{
    //change the name of the file
    //return same file or its copy with a different name
}

It would be good to have HttpPostedFileBase as a return type, however it can be sacrificed if needed.

Is there a way to do this through memory streams or anything else? I appreciate any help, thank you for taking your time to read this. :)


Solution

  • Well, I finally found a way that's really simple - I guess I was overthinking this a bit. I figured I'll just share the solution, since some of you might need it. I tested it and it works for me.

    You just have to create your own class HttpPostedFileBaseDerived that inherits from HttpPostedFileBase. The only difference between them is that you can make a constructor there.

        public class HttpPostedFileBaseDerived : HttpPostedFileBase
        {
            public HttpPostedFileBaseDerived(int contentLength, string contentType, string fileName, Stream inputStream)
            {
                ContentLength = contentLength;
                ContentType = contentType;
                FileName = fileName;
                InputStream = inputStream;
            }
            public override int ContentLength { get; }
    
            public override string ContentType { get; }
    
            public override string FileName { get; }
    
            public override Stream InputStream { get; }
    
            public override void SaveAs(string filename) { }
    
        }
    }
    

    Since constructor is not affected by ReadOnly, you can easily copy in the values from your original file object to your derived class's instance, while putting your new name in as well:

    HttpPostedFileBase renameFile(HttpPostedFileBase file, string newFileName)
    {
        string ext = Path.GetExtension(file.FileName); //don't forget the extension
    
        HttpPostedFileBaseDerived test = new HttpPostedFileBaseDerived(file.ContentLength, file.ContentType, (newFileName + ext), file.InputStream);
        return (HttpPostedFileBase)test; //cast it back to HttpPostedFileBase 
    }
    

    Once you are done you can type cast it back to HttpPostedFileBase so you wouldn't have to change any other code that you already have.

    Hope this helps to anyone in the future. Also thanks to Manoj Choudhari for his answer, thanks to I learned of where not to look for the solution.