Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create file in memory not filesystem

Tags:

c#

.net

file

I am using a .NET library function that uploads files to a server, and takes as a parameter a path to a file. The data I want to send is small and constructed at runtime. I can save it to a temporary file and then upload it.

Since my application will be deployed in a variety of environments, and I don't know if I'll be able to create the temporary file reliably, it would be preferable to be able to pass in a path to a virtual file in memory.

I can't change the library; I know it executes the following on the file:

LibraryUploadFunction(string filename) {
    fileName = Path.GetFullPath(fileName);
    FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
    ...
}

Is it possible to avoid writing the file to disk?

Thanks

Edit:

The library call is Webclient.UploadFile, as pointed out in the answers, there are many workarounds possible, including using alternative libraries, of which there are many.

like image 284
Stefan Avatar asked May 03 '13 13:05

Stefan


3 Answers

No, your library is fundamentally inflexible in this aspect, by the fact that it uses FileStream.

Options:

  • Use a ramdrive and specify a path on that, in order to avoid actually hitting disk
  • Depending on where the library comes from, either request a change (if it's closed source) or just make the change if it's open source
  • Use a different library. (What's special about this one?)
like image 53
Jon Skeet Avatar answered Nov 15 '22 17:11

Jon Skeet


If the library exposes another method accepting a Stream, you could use a MemoryStream.

If it accepts a SafeFileHandle, you could use a MemoryMappedFile.

Otherwise, you'll have to be satisfied with a file on disk.

like image 22
Kendall Frey Avatar answered Nov 15 '22 15:11

Kendall Frey


If I understand you correctly, you want to use one of the other WebClient.Upload* methods. For example, if you have your data in a byte[], use UploadData.

Another option, if you want to upload the data as a stream is to use OpenWrite.

like image 39
svick Avatar answered Nov 15 '22 16:11

svick