繁体   English   中英

ReadAllBytes,用于在Windows Phone 8 c#中将文件上传到Google云端硬盘

[英]ReadAllBytes for uploading file to Google Drive in Windows Phone 8 c#

我已经编码了上传过程中的授权部分,但是我不知道授权后如何上传文件。 我想上传图片,但首先我会先尝试使用txt文件。

        Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
        body.Title = "My document";
        body.Description = "A test document";
        body.MimeType = "text/plain";

        byte[] byteArray = System.IO.File.ReadAllBytes("document.txt");
        System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);

        FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "text/plain");
        request.Upload();

        Google.Apis.Drive.v2.Data.File file = request.ResponseBody;

我已经在互联网上到处找到了上面的代码。 但是看起来它仅用于Windows窗体,因为System.IO.File的文档没有说它支持Windows Phone。 我的问题始于ReadAllBytes。 它说'System.IO.File' does not contain a definition for 'ReadAllBytes' 那么,我该如何读取allbytes?

有任何想法吗? 谢谢。

如果您需要按照下面的代码行那样在API中传递MemoryStream,

FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "text/plain");

那为什么要转换为byte [] ..? 您可以像这样将文件直接转换为MemoryStream:

var a = System.IO.File.OpenRead("document.txt");
System.IO.MemoryStream stream = new System.IO.MemoryStream();
a.CopyTo(stream);

然后,您可以直接将stream作为参数传递。

FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "text/plain");
request.Upload();

Google.Apis.Drive.v2.Data.File file = request.ResponseBody;

现在,我建议不要在Windows Phone 8中使用System.IO.File ,而应使用Windows.Storage.StorageFile ,该文件包含操纵文件的正确实现,无论该文件位于InstalledLocation还是IsolatedStorage

编辑:-

有关更多信息,以下是如何将文件读取到MemoryStream:

        using (MemoryStream ms1 = new MemoryStream())
        {
            using (FileStream file = new FileStream("document.txt", FileMode.Open, FileAccess.Read))
            {
                byte[] bytes = new byte[file.Length];
                file.Read(bytes, 0, (int)file.Length);
                ms1.Write(bytes, 0, (int)file.Length);
            }
        }

有关更多代码,请在此处简要介绍您的方案。希望对您有所帮助。

Windows Phone(和Store Apps)使用StorageFiles,因此您必须使用与System.IO不同的API。 有了StorageFile后,System.IO命名空间中就有扩展方法,这些扩展方法会将StorageFile的IRandomAccessStream转换为所有示例都使用的标准Stream。 此处的示例代码使用OpenStreamForReadAsync来获取Stream。 然后,您可以获取字节,或直接使用流。

var file = await ApplicationData.Current.LocalFolder.GetFileAsync("sample.txt");
using (var stream = await file.OpenStreamForReadAsync())
{
    //ideally just copy this stream to the the request stream
    //or use an HttpClient and request with StreamContent(stream).

    //if you need the bytes, you can do this
    var buffer = new byte[stream.Length];
    await stream.ReadAsync(buffer, 0, buffer.Length);
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM