FileOutputStream将0字节写入Google云端硬盘

时间:2018-06-25 02:16:08

标签: android xamarin xamarin.android android-contentprovider

步骤1:获取要保存的文件(在这种情况下为小png)。

var fileBytes = getFileBytes();

步骤2:从Google云端硬盘获取内容uri。

var intent = new Intent(Intent.ActionCreateDocument);
intent.AddCategory(Intent.CategoryOpenable);
intent.SetType(mimeType);
intent.PutExtra(Intent.ExtraTitle, fileNameWithExtension);
StartActivityForResult(Intent.CreateChooser(intent, "Select Save Location"), 43);

步骤3:创建一个FileOutputStream来处理内容提供​​商的写作。

protected override async void OnActivityResult (int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
    base.OnActivityResult (requestCode, resultCode, data);

    if (resultCode == Result.Canceled && requestCode == 43) {
        using (var pFD = ContentResolver.OpenFileDescriptor(data.Data, "w"))
        using (var outputSteam = new FileOutputStream(pFD.FileDescriptor))
        {
            await outputSteam.WriteAsync(fileBytes);
        }
    }
}

如果我将文件保存在本地,则此代码有效。但是,当我将文件保存到Google云端硬盘时,该文件存在,但它有0个字节。这是令人担忧的,因为如果我这样做正确,并且无法在Google云端硬盘上运行,那么谁知道它是否可以在其他内容提供商上运行。

为清楚起见,它将在步骤2中创建文件。那么,步骤3中的代码正确吗?同样,如果我将文件保存在本地,它确实可以工作。

0 个答案:

没有答案