You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中将Android.Net.Uri转换为字节数组(Xamarin.Android)

Convert Android.Net.Uri to Byte Array in Xamarin.Android

Got it, let's solve this for your Xamarin.Android app! Converting an Android.Net.Uri (from your file picker result) to a byte array is key for multipart file uploads, and here's the clean C# implementation you need—no Java translations required.

Step-by-Step Implementation

First, update your OnActivityResult method to call a helper function that handles the Uri-to-byte-array conversion. We'll use Android's ContentResolver to safely access the file content (this works for all Uri sources, like the file manager, gallery, etc., even if the Uri doesn't point directly to a filesystem path).

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

    // Make sure we have a valid result and data
    if (resultCode == Result.Ok && data?.Data != null)
    {
        Android.Net.Uri attachmentUri = data.Data;
        try
        {
            byte[] fileBytes = await ConvertUriToByteArrayAsync(attachmentUri);
            
            // Use fileBytes for your multipart upload logic here
            // Example: Pass to your HTTP client's multipart content
        }
        catch (Exception ex)
        {
            // Handle errors (e.g., permission issues, file not found)
            Console.WriteLine($"Error converting Uri to bytes: {ex.Message}");
        }
    }
}

private async Task<byte[]> ConvertUriToByteArrayAsync(Android.Net.Uri uri)
{
    if (uri == null)
        throw new ArgumentNullException(nameof(uri));

    // Use ContentResolver to open a stream to the Uri content
    using (var inputStream = ContentResolver.OpenInputStream(uri))
    using (var memoryStream = new MemoryStream())
    {
        // Copy the input stream to memory stream asynchronously
        await inputStream.CopyToAsync(memoryStream);
        // Convert memory stream to byte array
        return memoryStream.ToArray();
    }
}

Key Notes

  • Why ContentResolver? Some Uris (like those from MediaStore) don't map directly to a filesystem path. Using OpenInputStream ensures you can access the file content regardless of where it comes from.
  • Async/Await: We use async methods to avoid blocking the UI thread—critical for preventing ANRs (Application Not Responding) in Android.
  • Permissions: If you're targeting Android versions below 10, ensure you've requested the READ_EXTERNAL_STORAGE permission. For Android 10+, scoped storage handles most cases automatically when using the system file picker (since the picker grants temporary access to the selected file).

内容的提问来源于stack exchange,提问作者Thamarai T

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:51:31