我需要将类型 Plugin.Media.Abstractions.MediaFile
转换为 Windows.Storage.StorageFile
.
原因是我想要通过路径上传到服务器的 MediaFile
,但是在UWP中你必须使用StorageFiles而不是文件路径,否则UWP不会't know that the user has the permission for this file and just denies the access. So I want to convert the MediaFile to a StorageFile to be able to create a copy of the file in the temporary folder of the user. Files in this folder can be accessed by the file'的路径 .
这就是我尝试过的:
Stream stream = _mediaFile.GetStream();
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
string streamText = reader.ReadToEnd();
_websocketManager.sendFileMessage(_selectedChat.chatId, _nachrichttext, streamText);
sendFileMessage()
是一个来自接口的方法,所以参数必须是一个字符串,我可以't change that. Originally this string is supposed to be the path, so it'一个廉价的解决方法由我但是's legit for what I' m试图实现 .
在WebsocketManager中,这是我的方法 sendFileMessage()
:
byte[] byteArray = Encoding.UTF8.GetBytes(streamText);
MemoryStream stream = new MemoryStream(byteArray);
StorageFolder temporaryFolder = ApplicationData.Current.TemporaryFolder;
var temporaryFile = await temporaryFolder.CreateFileAsync("temporaryFile", CreationCollisionOption.ReplaceExisting);
using (var fileStream = File.Create(temporaryFolder.Path + "\\TemporaryFile")) // TODO: How to data type? (.png, .jpg, ...)
{
stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(fileStream);
}
string filePath = temporaryFile.Path;
string remoteFilePath = null;
if (!string.IsNullOrEmpty(filePath))
{
await StorageFile.GetFileFromPathAsync(filePath);
remoteFilePath = await uploadFile(filePath);
}
dataWriter.WriteString(WebsocketRequestFactory.Create(SocketEventsEnm.MESSAGE_OUT, chatId, message, remoteFilePath, TypeEnm.IMAGE));
await SendData(dataWriter);
await temporaryFile.DeleteAsync();
另外,正如我在代码中评论的那样,我需要找出 MediaFile
是哪种数据类型(.png,.jpg等) .
1 回答
您可以参考xamarin官方文档Working with Files来读取和写入文件,我们需要在每个平台上使用本机文件API .
对于UWP应用程序,您可以在便携式项目中创建一个接口
ISaveAndLoad
,如下所示:然后在你的UWP应用程序中创建一个类继承并实现这个
ISaveAndLoad
接口,如下所示:最后,当您选择图像时,可以将
MediaFile
转换为StorageFile
并获取临时文件的路径,如下所示: