如何将 CloudFileStream 转换为 FileStream?
How to convert CloudFileStream to FileStream?
我有一个使用 IO.FileStream
读取文件的应用程序。我们正在将存储迁移到 Azure 文件存储。如何在 C# 中将 CloudFileStream
转换为 IO.FileStream
?
由于这些 类 是兄弟姐妹(均派生自 Stream
)并且没有 parent/child 关系,因此没有直接的方法将一个转换为另一个。您需要使用本地文件才能使用 FileStream
而不是复制到 Azure 的 CloudFileStream.https://msdn.microsoft.com/en-us/library/system.io.path.gettempfilename(v=vs.110).aspx)
注释
- 通常最好使用
Stream
作为大多数方法的参数,因为您将能够处理更多类型(包括这两种)。
- 如果您计划在调用您的方法之前保留
FileStream
并复制 CloudFileStream
to/from lcal 文件的内容 - 使用 Path.GetTemplFileName ans 名称创建临时文件并确保操作完成后清理它们。
有 2 个可能的答案,具体取决于您想要做什么,
如果你想写一个 class 可以使用两种类型的流,那么最简单的方法是 class 围绕抽象 stream class这对所有流都是通用的
如果您想将数据从一个流复制到另一个流,则可以使用 CopyTo function 但是需要 .Net4 或更高版本
来自 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());
我有一个使用 IO.FileStream
读取文件的应用程序。我们正在将存储迁移到 Azure 文件存储。如何在 C# 中将 CloudFileStream
转换为 IO.FileStream
?
由于这些 类 是兄弟姐妹(均派生自 Stream
)并且没有 parent/child 关系,因此没有直接的方法将一个转换为另一个。您需要使用本地文件才能使用 FileStream
而不是复制到 Azure 的 CloudFileStream.https://msdn.microsoft.com/en-us/library/system.io.path.gettempfilename(v=vs.110).aspx)
注释
- 通常最好使用
Stream
作为大多数方法的参数,因为您将能够处理更多类型(包括这两种)。 - 如果您计划在调用您的方法之前保留
FileStream
并复制CloudFileStream
to/from lcal 文件的内容 - 使用 Path.GetTemplFileName ans 名称创建临时文件并确保操作完成后清理它们。
有 2 个可能的答案,具体取决于您想要做什么,
如果你想写一个 class 可以使用两种类型的流,那么最简单的方法是 class 围绕抽象 stream class这对所有流都是通用的
如果您想将数据从一个流复制到另一个流,则可以使用 CopyTo function 但是需要 .Net4 或更高版本
来自 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());