Monday, September 5, 2011

Lessons learned porting C# code from Windows to MacOS and iOS

I started porting C# code to MacOS and iOS and found some interesting problems, how to correct them or what best practices to follow, to have the same code running correctly on all operating systems. I will use this post to gather all my findings.


  • NewLine
    You probably know that text file line separator on Windows are defined as CR+LF and on MacOS are defined as LF. The property System.Environment.NewLine will return the right value, but. Look at this code below
    var t = b.ToString();
    if(t.EndsWith(System.Environment.NewLine))
        t = t.Substring(0, t.Length-2);
    
    I supposed that the length of NewLine is always 2. Wrong. Here is the right way.
    var t = b.ToString();
    if(t.EndsWith(System.Environment.NewLine))
        t = t.Substring(0, t.Length-System.Environment.NewLine.Length);
    


  • TEMP Folder
    When I need to create a temporary file, I always used the following
    var t = b.ToString();
    var fileName  = String.Format(@"{0}\DSSharpLibrary_UnitTests.txt", Environment.GetEnvironmentVariable("TEMP"));
    
    Well this code does not work on MacOS, but you can use the following code which will work on Windows, MacOS and iOS.
    var t = b.ToString();
    var fileName  = String.Format(@"{0}DSSharpLibrary_UnitTests.txt", System.IO.Path.GetTempPath());
    
    Note that GetTempPath() will return a '\' at the end in Windows or a '/' at the end on MacOS. Do not prefix your file name with any slash.
  • No comments:

    Post a Comment