选择在Xamarin Forms

时间:2018-01-29 22:37:40

标签: c# xamarin.forms

我有一个Xamarin表单应用程序,我想保存文件,当用户在手机中打开文件管理器或手机连接到计算机时,应显示该文件。我读了这个article,但问题是文件存储到Environment.SpecialFolder.Personal,用户无法打开此路径。我也发现这个plugin完全一样。它将文件存储到路径Environment.SpecialFolder.Personal。当我尝试将文件保存在另一个位置时,我总是会收到错误消息:

  

访问路径' ..'被拒绝

我应该使用哪条路径来保存文件?

3 个答案:

答案 0 :(得分:5)

  

System.Environment.SpecialFolder.Personal类型映射到路径/data/data/[your.package.name]/files。这是您的应用程序的私人目录,因此您无法使用文件浏览器查看这些文件,除非它具有root权限。

因此,如果您希望用户找到该文件,则无法将该文件保存在Personal文件夹中,而是保存在另一个文件夹(例如Downloads)中:

string directory = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
string file = Path.Combine(directory, "yourfile.txt");

您还必须向AndroidManifest.xml添加权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

答案 1 :(得分:4)

以下是为Android,iOS和UWP保存图片的代码:

机器人:

public void SaveImage(string filepath)
{
    var imageData = System.IO.File.ReadAllBytes(filepath);
    var dir = Android.OS.Environment.GetExternalStoragePublicDirectory(
    Android.OS.Environment.DirectoryDcim);
    var pictures = dir.AbsolutePath;
    var filename = System.DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg";
    var newFilepath = System.IO.Path.Combine(pictures, filename);

    System.IO.File.WriteAllBytes(newFilepath, imageData);
    //mediascan adds the saved image into the gallery
    var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
    mediaScanIntent.SetData(Android.Net.Uri.FromFile(new Java.IO.File(newFilepath)));
    Xamarin.Forms.Forms.Context.SendBroadcast(mediaScanIntent);
}

的iOS:

public async void SaveImage(string filepath)
{
    // First, check to see if we have initially asked the user for permission 
    // to access their photo album.
    if (Photos.PHPhotoLibrary.AuthorizationStatus == 
        Photos.PHAuthorizationStatus.NotDetermined)
    {
        var status = 
            await Plugin.Permissions.CrossPermissions.Current.RequestPermissionsAsync(
                Plugin.Permissions.Abstractions.Permission.Photos);
    }

    if (Photos.PHPhotoLibrary.AuthorizationStatus == 
        Photos.PHAuthorizationStatus.Authorized)
    {
        // We have permission to access their photo album, 
        // so we can go ahead and save the image.
        var imageData = System.IO.File.ReadAllBytes(filepath);
        var myImage = new UIImage(NSData.FromArray(imageData));

        myImage.SaveToPhotosAlbum((image, error) =>
        {
            if (error != null)
                System.Diagnostics.Debug.WriteLine(error.ToString());
        });
    }
}

UWP:

public async void SaveImage(string filepath)
{
    var imageData = System.IO.File.ReadAllBytes(filepath);
    var filename = System.DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg";

    if (Device.Idiom == TargetIdiom.Desktop)
    {
        var savePicker = new Windows.Storage.Pickers.FileSavePicker();
        savePicker.SuggestedStartLocation = 
            Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
        savePicker.SuggestedFileName = filename;
        savePicker.FileTypeChoices.Add("JPEG Image", new List<string>() { ".jpg" });

        var file = await savePicker.PickSaveFileAsync();

        if (file != null)
        {
            CachedFileManager.DeferUpdates(file);
            await FileIO.WriteBytesAsync(file, imageData);
            var status = await CachedFileManager.CompleteUpdatesAsync(file);

            if (status == Windows.Storage.Provider.FileUpdateStatus.Complete)
                System.Diagnostics.Debug.WriteLine("Saved successfully"));
        }
    }
    else
    {
        StorageFolder storageFolder = KnownFolders.SavedPictures;
        StorageFile sampleFile = await storageFolder.CreateFileAsync(
            filename + ".jpg", CreationCollisionOption.ReplaceExisting);
        await FileIO.WriteBytesAsync(sampleFile, imageData);
    }
}

请注意,对于iOS,我使用Plugin.Permissions nuget数据包来请求用户的许可。

答案 2 :(得分:0)

对于Android,@David Moškoř的答案非常有效。

对于IOS,我们可以使用以下路径:

Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "..", "Library"); 

但是必须在IOS项目的LSSupportsOpeningDocumentsInPlace文件中启用Supports Document BrowserInfo.plist才能使用户浏览保存的文件(当您打开Files时会显示应用并导航至On My iPhone