Xamarin.forms Xamarin表单:获取存储在共享项目上的图像文件的路径?

Xamarin.forms Xamarin表单:获取存储在共享项目上的图像文件的路径?,xamarin.forms,shared-project,Xamarin.forms,Shared Project,我正试图通过我的web服务将图像文件作为ByteArrayContent上传。我已将所有图像添加到共享项目中,并将构建操作设置为嵌入式资源 以下是我的代码: var fileBytes = File.ReadAllBytes("Avatars." + selectedAvatar); var byteContent = new ByteArrayContent(fileBytes); content.Add(byteContent, "file", sel

我正试图通过我的web服务将图像文件作为
ByteArrayContent
上传。我已将所有图像添加到共享项目中,并将构建操作设置为
嵌入式资源

以下是我的代码:

var fileBytes = File.ReadAllBytes("Avatars." + selectedAvatar);
var byteContent = new ByteArrayContent(fileBytes);
content.Add(byteContent, "file", selectedAvatar);
当我像上面那样尝试时,我得到了
System.IO.FileNotFoundException:找不到文件“/Projectname.Avatars.ic\u avatar01\u xx.png”

将图像直接添加到共享项目的文件夹中,如下图所示

:

我试着换衣服。在文件路径中使用/时,如下所示:

var fileBytes = File.ReadAllBytes("Avatars/" + selectedAvatar);
var byteContent = new ByteArrayContent(fileBytes);
content.Add(byteContent, "file", selectedAvatar);
但是在这种情况下,我得到了
System.IO.DirectoryNotFoundException:找不到路径的一部分“/Avatars/ic\u avatar01\u xx.png”

获取存储在共享项目中的图像文件路径的正确方法是什么?

还尝试了另一种方法:

string avatarFileName = "Avatars/" + selectedAvatar;
var assembly = typeof(ProfilePage).GetTypeInfo().Assembly;
var stream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{avatarFileName}");
content.Add(stream, "file", avatarFileName);
但在上述情况下,我得到以下错误:


如果您想上传带有流的图像,可以检查以下代码

private async Task<string> UploadImage(Stream FileStream)
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://your.url.com/");
            MultipartFormDataContent form = new MultipartFormDataContent();
            HttpContent content = new StringContent("fileToUpload");
            form.Add(content, "fileToUpload");
            content = new StreamContent(FileStream);
            content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                Name = "fileToUpload",
                FileName = "xxx.png"
            };
            form.Add(content);
            var response = await client.PostAsync("http://your.url.com/", form);
            return response.Content.ReadAsStringAsync().Result;
        }

只有将图像文件直接放入项目中,才能得到图像流。如果你想实现它,你需要把图像放在本地或sd卡上。检查。@LucasZhang MSFT是否可以将流转换为
System.Net.Http.HttpContent
?我需要通过服务以该格式传递数据。是否要使用httpclient上载图像流?从这里获得解决方案:@LucasZhang MSFT是的,我正在尝试上载图像
CrossFileUploader.Current.UploadFileAsync("<URL HERE>", new FilePathItem("<REQUEST FIELD NAME HERE>","<FILE PATH HERE>"), new Dictionary<string, string>()
            {
               {"<HEADER KEY HERE>" , "<HEADER VALUE HERE>"}
            }
);
string avatarFileName = "Avatars." + selectedAvatar;
var assembly = typeof(ProfilePage).GetTypeInfo().Assembly;
var stream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{avatarFileName}");
var streamContent = new StreamContent(stream);
content.Add(streamContent, "file", avatarFileName);