如何保存文件以便用户查看?

时间:2019-05-13 13:05:07

标签: xamarin.forms

我无法在Xamarin.forms文件中保存文件,以便用户可以在下载或文档中看到它。我已经设法使用 PCL 保存到隐藏文件中,但是我需要用户能够看到保存的文件。我可以用来访问可见文件夹并将文件保存在那里吗?

这不起作用:

string writeData = convertToString(data);
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string localFilename = "Data.csv";
string localPath = Path.Combine(documentsPath, localFilename);
File.WriteAllText(localPath, writeData);

2 个答案:

答案 0 :(得分:0)

当然,您可以将文件保存到可见文件夹。 根据文档: external storage。 例如,如果要将文件保存到“文档”文件夹,则可以按以下方式获取路径:

processed_names = (name.split('.')[0] for name in done_match)
d = dict.from_keys(processed_names, 1)

希望对您有帮助!

答案 1 :(得分:0)

在iOS和Android上采用不同的解决方案,并使用depencdeny加以区分。

Android

     public void saveFile(string fileName, string text)
     {
        string DocumentPath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).AbsolutePath;
        string filePath = Path.Combine(DocumentPath, fileName);
        File.WriteAllText(filePath, text);
     }

iOS:找到了一些代码,可以将其保存在iCLoud驱动器https://xamarinhelp.com/share-dialog-xamarin-forms/上:

     public class Share : IShare
{
    // MUST BE CALLED FROM THE UI THREAD
    public async Task Show(string filePath)
    {
        var items = new NSObject[] { NSUrl.FromFilename(filePath) };
        var activityController = new UIActivityViewController(items, null);
        var vc = GetVisibleViewController();

        NSString[] excludedActivityTypes = null;

        if (excludedActivityTypes != null && excludedActivityTypes.Length > 0)
            activityController.ExcludedActivityTypes = excludedActivityTypes;

        if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
        {
            if (activityController.PopoverPresentationController != null)
            {
                activityController.PopoverPresentationController.SourceView = vc.View;
            }
        }
        await vc.PresentViewControllerAsync(activityController, true);
    }

    UIViewController GetVisibleViewController()
    {
        var rootController = UIApplication.SharedApplication.KeyWindow.RootViewController;

        if (rootController.PresentedViewController == null)
            return rootController;

        if (rootController.PresentedViewController is UINavigationController)
        {
            return ((UINavigationController)rootController.PresentedViewController).TopViewController;
        }

        if (rootController.PresentedViewController is UITabBarController)
        {
            return ((UITabBarController)rootController.PresentedViewController).SelectedViewController;
        }

        return rootController.PresentedViewController;
    }
}