简体   繁体   中英

How to convert CloudFileStream to FileStream?

I have an application which uses IO.FileStream to read files. We are moving storage to Azure File storage. How do I convert CloudFileStream to IO.FileStream in c#?

there are 2 possible answers depending on what you want to do,

if you want to write a class that can work with both types of stream then the simplest way is to base that class around the abstract stream class which is common to all streams

if you want to copy data from one stream to another then you can use the CopyTo function however requires .Net4 or higher

from MSDN

// Create the streams.
MemoryStream destination = new MemoryStream();

using (FileStream source = File.Open(@"c:\temp\data.dat",
    FileMode.Open))
{

    Console.WriteLine("Source length: {0}", source.Length.ToString());

    // Copy source to destination.
    source.CopyTo(destination);
}

Console.WriteLine("Destination length: {0}", destination.Length.ToString());

Since these classes are siblings (both derive from Stream ) and do not have parent/child relationship there is no direct way to convert one to another. You need to use local file to use FileStream and than copy to Azure's CloudFileStream . https://msdn.microsoft.com/en-us/library/system.io.path.gettempfilename(v=vs.110).aspx )

Notes

  • it is generally better to use Stream as parameter to most methods as you'll be able to handle more types (including these two).
  • If you plan to keep FileStream and copy content of CloudFileStream to/from lcal file before calling your methods - create temporary files using Path.GetTemplFileName ans name and make sure to clean them up after operation is complete.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM