代码之家  ›  专栏  ›  技术社区  ›  Darius Buhai

不允许写入流C

  •  0
  • Darius Buhai  · 技术社区  · 8 年前

    我想使用streamwriter写入文件,但我的问题是流无法写入。我已经使用streamreader成功地读取了该文件,但是我不知道如何编写它。以下是我创建流的方式:

    var assembly = IntrospectionExtensions.GetTypeInfo(typeof(Login)).Assembly;
    Stream stream = assembly.GetManifestResourceStream("BSoft.Resources.LoggedHistory.json");
    

    stream.CanWrite
    

    返回false。 请帮助我,我正在使用.netportable v4.5,而且我也无法安装system.io.filesystem

    1 回复  |  直到 8 年前
        1
  •  0
  •   Darius Buhai    8 年前

    在做了一些调查之后,我发现了这个 documentation 非常有用。

    因此,主要问题是在.netportable中不能使用system.io.filesystem,因为ios、android和windows文件系统之间存在许多差异。所以你应该用 Dependency Service ,通过创建接口:

    ...
    namespace BSoft
    {
     public interface ISaveAndLoad
     {
        void SaveFile(string filename, string text);
        bool CheckExistingFile(string filename);
        string ReadFile(string filename);
     }
    }
    

    并为每个平台添加依赖项,以下是iOS的一个示例:

    网间网操作系统:

    ... 
    
    using System.IO;
    using Xamarin.Forms;
    using BSoft.iOS;
    
    [assembly: Dependency(typeof(SaveReadFiles_iOS))] /// !! Important
    namespace BSoft.iOS
    {
     public class SaveReadFiles_iOS : ISaveAndLoad
     {
        public SaveReadFiles_iOS(){}
    
        public void SaveFile(string filename, string text)
        {
            var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            var filePath = Path.Combine(documentsPath, filename);
            File.WriteAllText(filePath, text);
        }
    
        public bool CheckExistingFile(string filename)
        {
            var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            var filePath = Path.Combine(documentsPath, filename);
            return File.Exists(filePath);
        }
    
        public string ReadFile(string filename)
        {
            var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            var filePath = Path.Combine(documentsPath, filename);
            if(File.Exists(filePath))
                return File.ReadAllText(filePath);
            return "";
        }
       }
      }
    

    此外,还有更多因素需要考虑,比如在每个平台appdelegate类中添加xamarin.forms包并调用forms.init()。

    最后,您可以这样调用这些依赖项:

    DependencyService.Get<ISaveAndLoad>().CheckExistingFile("LoggedHistory.json")
    
    推荐文章