Search code examples
c#.netstreamportable-class-library

Writing to stream C# not allowed


I want to write to a file using StreamWriter, but my problem is that my stream cannot write. I have successfully read that file using StreamReader, but I cannot figure out how to write it. Here is how I created the stream:

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

And

stream.CanWrite

Returns false.

I am using .NETPortable v4.5, and I cannot install System.IO.FileSystem also


Solution

  • After doing some research, I found this documentation very useful.

    So the main problem is that in.NetPortable you cannot use System.IO.FileSystem, because there are many differences between iOS, android, and windows file systems. So you should use a Dependency Service, by creating an interface:

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

    And adding dependencies for each platform, here is an example for iOS:

    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 "";
        }
       }
      }
    

    Also, there are more factors to consider like adding xamarin. forms package and calling Forms.Init() in each platform AppDelegate class.

    Finally, you can use this dependency by calling them like this:

    DependencyService.Get<ISaveAndLoad>().CheckExistingFile("LoggedHistory.json")