【问题标题】:System.IO.File does not contain ReadAllBytes C#System.IO.File 不包含 ReadAllBytes C#
【发布时间】:2011-06-28 05:54:44
【问题描述】:

在 C# 中,我正在为 WP7 创建简单的 facebook 应用程序,但遇到了一个问题。

我正在尝试在相册或提要中上传图片。

代码:

FacebookMediaObject facebookUploader = new FacebookMediaObject { FileName = "SplashScreenImage.jpg", ContentType = "image/jpg" };

var bytes = System.IO.File.ReadAllBytes(Server.MapPath("~") + facebookUploader.FileName);
facebookUploader.SetValue(bytes);

错误:

  • System.IO.File 不包含 ReadAllBytes 的定义

【问题讨论】:

  • +1 将其作为一个单独的问题发布,其中包含代码。

标签: c# windows-phone-7


【解决方案1】:

你有几个问题。首先,Server.MapPath 不会为您提供文件位置(因为您不在 Web 应用程序中)。但是,一旦您知道要查找的文件路径(在 IsolatedStorage 中),您就可以执行以下操作以将文件作为字节数组读取:

    public byte[] ReadFile(String fileName)
    {
        byte[] bytes;
        using (IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication())
        {
            using (IsolatedStorageFileStream file = appStorage.OpenFile(fileName, FileMode.Open, FileAccess.Read))
            {
                bytes = new byte[file.Length];

                var count = 1024;
                var read = file.Read(bytes, 0, count);
                var blocks = 1;
                while(read > 0)
                {
                    read = file.Read(bytes, blocks * count, count); 
                    blocks += 1;
                }
            }
        }
        return bytes;
    }

【讨论】:

  • 我会为 isolatedStorageFileStream 使用“使用”块 - 并在循环中读取,而不是假设对 Read 的单个调用将获得所有内容。
  • 更新为流使用 using 块 - 感谢您的建议。
  • ... Aaannnd 再次更新以循环读取,因为我刚刚意识到文件的长度是 Int64,并且可能超出 Read 一次读取整个文件的能力。谢谢你让我诚实,乔恩。
  • @E.Z. Hart:那总是会读到数组的start。你需要不断更新你正在阅读的地方:)见yoda.arachsys.com/csharp/readbinary.html
  • 谢谢大家的回答。我会试试你的例子。
【解决方案2】:

我找到了解决办法。

代码:

string imageName = boxPostImage.Text;
StreamResourceInfo sri = null;
Uri jpegUri = new Uri(imageName, UriKind.Relative);
sri = Application.GetResourceStream(jpegUri);

try
{
    byte[] imageData = new byte[sri.Stream.Length];
    sri.Stream.Read(imageData, 0, System.Convert.ToInt32(sri.Stream.Length));

    FacebookMediaObject fbUpload = new FacebookMediaObject
    {
         FileName = imageName,
         ContentType = "image/jpg"
    };
    fbUpload.SetValue(imageData);


    IDictionary<string, object> parameters = new Dictionary<string, object>();
    parameters.Add("access_token", _AccessToken);
    parameters.Add("source", fbUpload);

    //_fbClient.PostAsync("/"+MainPage._albumId+"/photos", parameters);
    _fbClient.PostAsync("/me/photos", parameters);


    MessageBox.Show("Image has been posted successfully..");
}
catch (Exception error)
{
    MessageBox.Show("Sorry, there's an error occured, please try again.");
}

【讨论】:

    猜你喜欢
    • 2023-03-13
    • 2012-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多