如何在Android和IOS上创建目录?

问题描述 投票:0回答:1

我创建了一个Xamarin应用,我想序列化一些数据。适用于Android的FileWorker类:​​

public class FileWorker : IFileWorker
{
    public Task<IEnumerable<string>> GetFilesAsync(string folder)
    {
        IEnumerable<string> filenames = from filepath in Directory.EnumerateFiles(GetDocsPath() + "/" + folder)
                                        select Path.GetFileName(filepath);
        return Task<IEnumerable<string>>.FromResult(filenames);
    }

    string GetFilePath(string filename)
    {
        return Path.Combine(GetDocsPath(), filename);
    }

    string GetDocsPath()
    {
        return System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
    }

    public Task SerializeAsync<T>(string filename, T obj)
    {
        string filepath = GetFilePath(filename);
        DataContractJsonSerializer formatter = new DataContractJsonSerializer(typeof(T));
        FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate);
        formatter.WriteObject(fs, obj);
        return Task.FromResult(true);
    }

    public Task<T> DeserializeAsync<T>(string filename)
    {
        DataContractJsonSerializer formatter = new DataContractJsonSerializer(typeof(T));
        T obj;
        FileStream fs = new FileStream(filename, FileMode.OpenOrCreate);
        obj = (T)formatter.ReadObject(fs);
        return Task.FromResult(obj);
    }
}

和添加方法:

public async void AddObjectAsync(object obj)
{
    var fv = DependencyService.Get<IFileWorker>();
    string path = AppSettings.ObjectsFolder + "/";
    try
    {
        await fv.SerializeAsync(path + "obj", obj);
    }
    catch (Exception e) { }
}

但是我在此函数中捕获了异常:

System.IO.DirectoryNotFoundException

如何在Android(和IOS,如果可能出现相同的异常)上创建此目录?

c# file xamarin xamarin.android xamarin.ios
1个回答
0
投票

您可以使用常规的C#System.IO方法

© www.soinside.com 2019 - 2024. All rights reserved.