无法从FileStream写入

时间:2014-09-25 07:37:13

标签: c# silverlight

我想从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上,它似乎正在编写文件:here

OpenWrite()也会出现访问错误。

还有另一种方法可以将FileInfo文档转换为字节吗?

1 个答案:

答案 0 :(得分:2)

要将文件读入byte [],简单方法是:

 byte[] myByteArray = File.ReadAllBytes(myFileInfo.FullName);

正如@Dmitry Bychenko所说,你试着写一个以readonly方式打开的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);
         }
     }
}

在你的情况下,我会投票给第一个例子,因为它易于阅读并完美地隐藏了流内容。