首页 > 解决方案 > 在 Xamarin UWP 应用程序中从远程网络共享打开文件

问题描述

有没有办法从 Xamarin UWP 应用程序中的远程网络共享打开文件。?

我们尝试使用 Xamarin 文件选择器,但它包括用户选择文件。

private void OpenFile()
{
    FileData fileData = await CrossFilePicker.Current.PickFile();
    string fileName = fileData.FileName;
    string contents = System.Text.Encoding.UTF8.GetString(fileData.DataArray);
 }

我们希望如果用户单击路径,则文件将以读取模式显示。

标签: xamarinuwpcross-platformfilepicker

解决方案


有没有办法从 Xamarin UWP 应用程序中的远程网络共享打开文件。?

UWP 提供broadFileSystemAccess了使用Windows.Storage namespace. 您需要在访问之前添加受限broadFileSystemAccess功能。

<Package
  ...
  xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
  IgnorableNamespaces="uap mp rescap">

...
<Capabilities>
    <rescap:Capability Name="broadFileSystemAccess" />
</Capabilities>

如果要获取 中的文件,则.NET Standard需要创建一个DependencyService.

在您的.NET Standard.

文件访问

public interface IFileAccess
 {
     Task<FileData> GetFileStreamFormPath(string Path);
 }
 public class FileData
 {
     public byte[] DataArray { get; set; }
     public string FileName { get; set; }
     public string FilePath { get; set; }
 }

在原生 UWP 项目中实现IFileAccess接口。

文件访问实现

[assembly: Xamarin.Forms.Dependency(typeof(FileAccessImplementation))]
namespace App6.UWP
{
    public class FileAccessImplementation : IFileAccess
    {
        public async Task<FileData> GetFileStreamFormPath(string Path)
        {
            var file = await StorageFile.GetFileFromPathAsync(Path);
            byte[] fileBytes = null;
            if (file == null) return null;
            using (var stream = await file.OpenReadAsync())
            {
                fileBytes = new byte[stream.Size];
                using (var reader = new DataReader(stream))
                {
                    await reader.LoadAsync((uint)stream.Size);
                    reader.ReadBytes(fileBytes);
                }
            }

            var FileData = new FileData()
            {
                FileName = file.Name,
                FilePath = file.Path,
                DataArray = fileBytes
            };
            return FileData;
        }
    }
}

用法

var file = DependencyService.Get<IFileAccess>().GetFileStreamFormPath(@"\\remote\folder\setup.exe");

推荐阅读