Read and write a text file with Netduino IoT

Tags: netduinoiot

enter image description here

One interesting topic about Netduino is that it has a built-in micro SD card module. It means that you can read and write files without any external modules.

Just an idea, you can create these following projects easily:

  • Read/Write log files Collect information from sensors, e.g. temperature, humidity, and PH values
  • Log values with date and time
  • Persist some information and send data in a batch to a server periodically to save battery by not connecting to the server too often

Let’s start creating a Netduino project to read and write a text file.

Create a new console project named "NetduinoReadWriteFile".

new project

Reference these DLLs in the project

  • Microsoft.SPOT.IO
  • SecretLabs.NETMF.IO
  • System.IO

Add NetMf.CommonExtensions source code to the project. We have the Nuget package “NetMf.CommonExtensions” but it does not work with .NET Micro 4.3.0. It requires a lower version of .NET Micro. Therefore, we need to compile it with .NET Micro 4.3.0.

I have forked NetMf.CommonExtensions and will do a Nuget package later. You may find the source code of NetMf.CommonExtensions in the repository of this DEMO.

Result of all references in the project:

enter image description here

A little talk about SD card.

When an SD card is inserted into the Netduino board, it is mounted as the SD volume. So for example, a file called log.txt in the root directory of the micro SD card will be accessed with the following path:

var path = Path.Combine("SD","log.txt");

The other thing to keep in mind is that after writing to a file, the FlushAll() method on the volume object must be called in order to force writing to a text file. Otherwise, the file might not be fully written.

Go back to the project, add this source code:

using Microsoft.SPOT;
using System.IO;
using Microsoft.SPOT.IO;
using System.Text;
using System;
using NetMf.CommonExtensions;

namespace NetduinoReadWriteFile
{
    public class Program
    {
        const string volumnName = "SD";
        private static readonly VolumeInfo volume = new VolumeInfo(volumnName);

        public static void Main()
        {
            ValidateSDVolumn();

            var path = Path.Combine(volumnName, "log.txt");
            File.Delete(path); //Delete file if exist

            //first write
            var textValue = StringUtility.Format("{0} Hello world 1\n", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"));
            WriteTextToFile(path, textValue);

            //second write to the same file
            textValue = StringUtility.Format("{0} Hello world 2\n", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"));
            WriteTextToFile(path, textValue);

            var readTextValue = ReadTextFromFile(path);
            Debug.Print(readTextValue);
        }

        private static void WriteTextToFile(string path, string textValue)
        {
            //more information about FileStream https://docs.microsoft.com/en-us/previous-versions/windows/embedded/y0bs3w9t%28v%3dvs.102%29
            //More information for FileMode Enumeration https://docs.microsoft.com/en-us/previous-versions/windows/embedded/6b40c5ay(v%3dvs.102)

            using (var fileStream = new FileStream(
                path,
                FileMode.Append, //Opens the file if it exists and seeks to the end of the file, or creates a new file. 
                FileAccess.Write))
            {
                //Write some text to a file
                //Use StringUtility from NetMf.CommonExtensions to format string
                var byteData = Encoding.UTF8.GetBytes(textValue);
                fileStream.Write(byteData, 0, byteData.Length);

                //Must call flush to write immediately. 
                //Otherwise, there's no guarantee as to when the file is written. 
                volume.FlushAll();
            }
        }

        private static string ReadTextFromFile(string path)
        {
            using (var streamReader = new StreamReader(path))
            {
                // read all texts from log file
                var stringData = streamReader.ReadToEnd();
                return stringData;
            }
        }

        private static void ValidateSDVolumn()
        {
            // check to see if there's an SD card inserted
            if (volume == null)
            {
                throw new InvalidOperationException("No SD volumn, make sure you have inserted a SD card");
            }
        }
    }
}

Connect the Netduino board to your computer with a USB cable. Go to the property window and select the .NET Micro Framework tab and select the following options:

  • Transport: USB
  • Device: Netduino3_Netduino

Press F5 to start the program with debugging. This will compile your source code, then upload the program to the board in debug mode which will show you messages in the output window.

enter image description here

Interesting points:

  • Use the FileMode.Append enumeration when working with FileStream to create a file if it doesn’t exist and continue writing values to the existing file.
  • Two messages get written to a text file because of the FileMode.Append enumeration
  • DateTime.UtcNow always returns the same value, we can fix it with a real time clock module which I will show you in an upcoming blog post.

Download source code

https://github.com/codesanook/NetduinoReadWriteFile

Credit