Main Site Documentation

.txt file help


#1

I am attempting to code a text log file that is stored on the PandaII SD card. the issue that I have is that I only get one line of text regardless of how many write attempts I make. What is my issue? Also I would like to write the new lines at the end of the file. All guidance appreciated!!!

Thanks,

K


public bool UpdateSD(string fileName, string dataToFile)
        {
            SDCard = new PersistentStorage("SD");
            SDCard.MountFileSystem();

            if (VolumeInfo.GetVolumes()[0].IsFormatted)
                try
                {
                    string root = VolumeInfo.GetVolumes()[0].RootDirectory;
                    string fileToWrite = root + @ "\" + fileName;
                    FileStream dataWriter = new FileStream(fileToWrite, FileMode.OpenOrCreate, FileAccess.Write);
                    byte[] data = Encoding.UTF8.GetBytes(dataToFile);
                    dataWriter.Write(data, 0, data.Length);
                    dataWriter.Close();
                }
                catch
                {
                    Debug.Print("Write to SD failed");
                    return false;
                }
            Thread.Sleep(2);
            SDCard.Dispose();
            return true;
        }


#2

You need to do a \n that will give you a new line. Alternatively you can do a \r\n. Either way.


#3

That is in my code already with no joy. I have several sections of code that that call the function (All instantiate a new object of ‘UpDateSD’) and if I pass multiple lines at the same time it seems to work for that instance. All sections of the code seem work if I am writing to [italic]different[/italic] files will not work if I am trying to write to the same file. I tried Thread.Sleep(20) just incase the instances are trying to access the SD card at the same time and that didn’t work. Here is an example of the code that I am using:

try
            {
                timeFlag = getTime.NTPTime("time-a.nist.gov", -300);
                Controls sd1 = new Controls();
                sd1.UpdateSD("log.txt", "\r\nTime set via \"time-a.nist.gov\". New time is: " + DateTime.Now);
                //Thread.Sleep(20); 
            }

#4

You need to change position of your file cursor to the end before writting inside it !

try: dataWriter.Seek(0, SeekOrigin.End);

just after creating the dataWriter object…


#5

Or in your case you can use FileMode.Append that way cursor is moved at the end during opening of the existing file.