[英]Can't Write from FileStream
我正在尝试从FileInfo
获取byte []。
在这里, FileInfo
(fi)是我放入Silverlight应用程序的文件。
因此,正如在msnd上发现的,我正在这样做:
byte[] b = new byte[fi.Length];
UTF8Encoding temp = new UTF8Encoding(true);
//Open the stream and read it back.
using (FileStream fs = fi.OpenRead())
{
while (fs.Read(b, 0, b.Length) > 0)
{
Console.WriteLine(temp.GetString(b));
}
}
但是,按照它的保护级别,我不能使用它。
所以,我这样做了:
byte[] b = new byte[fi.Length];
UTF8Encoding temp = new UTF8Encoding(true);
//Open the stream and read it back.
using (FileStream fs = fi.OpenRead())
{
while (fs.Read(b, 0, b.Length) > 0)
{
fs.Write(b, 0, b.Length);
}
}
但是我从FileStream
收到了无法写入的消息。
为什么我无法将我放入应用程序的文件写入一个字节? 删除文件后,它将成为FileInfo。
为什么我使用OpenRead()
? 因为在msdn上,看来它正在写文件: 这里
OpenWrite()
也会引发访问错误。
还有另一种方法可以将FileInfo文档转换为字节吗?
要将文件读入byte [],简单的方法是:
byte[] myByteArray = File.ReadAllBytes(myFileInfo.FullName);
正如@Dmitry Bychenko早已指出的那样,您尝试写入以只读方式打开的FileStream。 另一件事是您要写入读取的相同FileStream。
要通过更正尝试来解决问题,您可以执行以下操作:
byte[] b = new byte[fi.Length];
UTF8Encoding temp = new UTF8Encoding(true);
//Open the stream and read it back.
using (FileStream fs = fi.OpenRead())
{
using (MemoryStream ms = new MemoryStream(b))
{
while (fs.Read(b, 0, b.Length) > 0)
{
ms.Write(b, 0, b.Length);
}
}
}
在您的情况下,我将投票支持第一个示例,因为它易于阅读,并且完美地隐藏了流内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.