使用C#将文件(从流)保存到磁盘

21

可能重复:
如何将流保存到文件中?

我有一个流对象,它可能是图像或文件(msword、pdf),我决定以非常不同的方式处理这两种类型,因为我可能想要优化/压缩/调整大小/生成缩略图等。我调用特定的方法将图像保存到磁盘上,代码如下:

var file = StreamObject;

//if content-type == jpeg, png, bmp do...
    Image _image = Image.FromStream(file);
    _image.Save(path);

//if pdf, word do...

我该如何实际保存Word和PDF文档?

//multimedia/ video?

我已经找了(可能不够努力),但是我无法在任何地方找到它...


如果有任何问题,请查看这里。http://stackoverflow.com/questions/13100666/access-assets-from-monodroid-class-library/17824673#17824673 - Nelson Brian
6个回答

27
如果您正在使用 .NET 4.0 或更高版本,您可以使用此方法:
public static void CopyStream(Stream input, Stream output)
{
    input.CopyTo(output);
}

如果没有的话,使用这个:

public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[8 * 1024];
    int len;
    while ( (len = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write(buffer, 0, len);
    }    
}

以下是如何使用它:

using (FileStream output = File.OpenWrite(path))
{
    CopyStream(input, output);
}

5
因为以上代码是从 这个 Stack Overflow 回答 中复制过来的,所以我认为应该提供对原答案的引用。 - Christofer Eliasson
6
你确定吗?也许是从这里?或者可能是从Spring.NET源代码中?我猜这个实现甚至更旧。也许在那时候我使用了Jon答案中的代码,但我不能确定,因为那已经快4年了 ;) - rotman

23

对于文件类型,您可以依赖于FileExtentions,并且要将其写入磁盘,您可以使用BinaryWriterFileStream

示例(假设您已经有一个流):

FileStream fileStream = File.Create(fileFullPath, (int)stream.Length);
// Initialize the bytes array with the stream length and then fill it with data
byte[] bytesInStream = new byte[stream.Length];
stream.Read(bytesInStream, 0, bytesInStream.Length);    
// Use write method to write to the file specified above
fileStream.Write(bytesInStream, 0, bytesInStream.Length);
//Close the filestream
fileStream.Close();

最好将FileStream放在using语句内部,并且也将MemoryStream(bytesInStream)放在using语句内部。 - kimbaudi
9
我将此代码标记为危险代码Stream.Read不能保证它会读取指定长度(bytesInStream.Length)的数据。这就是为什么它返回一个实际读取量的值。如果忽略了这个返回值并且在amtReturned < bytesInStream.Length的情况下没有正确处理,那么这段代码就是一个危险的维护隐患,有时可能会工作(对于短流),但迟早会爆炸。不要使用这段代码 - spender

4
我必须引用c#大师Jon Skeet的话:
最简单的方法是打开一个文件流,然后使用以下代码: ``` byte[] data = memoryStream.ToArray(); fileStream.Write(data, 0, data.Length); ```
尽管如此,这种方式相对低效,因为它涉及复制缓冲区。对于大量数据,建议使用以下代码: ``` fileStream.Write(memoryStream.GetBuffer(), 0, memoryStream.Position); ```

2

关于filestream:

//Check if the directory exists
if (!System.IO.Directory.Exists(@"C:\yourDirectory"))
{
    System.IO.Directory.CreateDirectory(@"C:\yourDirectory");
}

//Write the file
using (System.IO.StreamWriter outfile = new System.IO.StreamWriter(@"C:\yourDirectory\yourFile.txt"))
{
    outfile.Write(yourFileAsString);
}

0

只需使用简单的文件流操作即可完成。

var sr1 = new FileStream(FilePath, FileMode.Create);
                sr1.Write(_UploadFile.File, 0, _UploadFile.File.Length);
                sr1.Close();
                sr1.Dispose();

_UploadFile.File是一个字节数组,FilePath中您可以指定文件扩展名。


0
如果数据已经有效且包含PDF、Word或图像文件,则可以使用StreamWriter保存它。

2
有没有任何代码示例?我目前有:StreamWriter filewriter = new StreamWriter(file); 我想将其保存到磁盘上的特定位置。 - Haroon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接