Appending to a file

I am having some luck writing to a usb stick file, but only the “first” write seems to come through…i want to eventually have a loop that appends more & more information…this simple example only seems to append garbage…i only get the first message (“four score and”);…where is it going wrong?

 // Assume one storage device is available, 
                // access it through NETMF
                string rootDirectory = VolumeInfo.GetVolumes()[0].RootDirectory;
                FileStream FileHandle = new FileStream(rootDirectory + @ "\hellome.txt", FileMode.Create);
                byte[] data = Encoding.UTF8.GetBytes("four score and");
                byte[] data1 = Encoding.UTF8.GetBytes(" seven hundred years ago");
                // write the data and close the file
                FileHandle.Write(data, 0, data.Length);
                FileHandle.Close();

                FileHandle = new FileStream(rootDirectory + @ "\hellome.txt", FileMode.Append);
                FileHandle.Write(data1, 0, data1.Length);
                FileHandle.Close();

                // if we need to unmount
                ps.UnmountFileSystem();

Please, take a look at this: http://www.tinyclr.com/codeshare/entry/319

What you are trying to accomplish is on codeshare, ready for you to use.

Well I did take a look & stole this

       fileStream = new FileStream(USBpath, FileMode.Append)

 fileStream.Write(data, 0, data.Length);

but sill no luck…where is it going wrong?

You close the FileHandle but you didn’t dispose it.

try:


FileHandle.Close();
FileHandle.Dispose();
FileStream FileHandle = new FileStream(rootDirectory + @ "\hellome.txt", FileMode.Append);

You can also add this at the end:

VolumeInfo.GetVolumes()[0].FlushAll();

neither of these additions worked properly to append (do 2 writes) to a file.

  1. the first write always works and appear in the file
    2)the second gives garbage or strangely has a piece of some prior test phrase that was used, even if it that made using a different file name.
    I got: four score andll go in the file! (the last part was a phrase used with a different file name)

The code:

    // access it through NETMF
                string rootDirectory = VolumeInfo.GetVolumes()[0].RootDirectory;
                FileStream FileHandle = new FileStream(rootDirectory + @ "\hellome1.txt", FileMode.Create);
                byte[] data = Encoding.UTF8.GetBytes("four score and");
                byte[] data1 = Encoding.UTF8.GetBytes(" seven hundred years ago");
                // write the data and close the file
                FileHandle.Write(data, 0, data.Length);
                FileHandle.Close();
                FileHandle.Dispose();
                FileHandle = new FileStream(rootDirectory + @ "\hellome1.txt", FileMode.Append);
                FileHandle.Write(data1, 0, data1.Length);
                FileHandle.Close();
                FileHandle.Dispose();
                VolumeInfo.GetVolumes()[0].FlushAll();
                // if we need to unmount
                ps.UnmountFileSystem();
             

Are you sure this is exactly the code you run on your platform?

After disposing FileHandle you should not be abble to run:

FileHandle = new FileStream(rootDirectory + @ "\hellome1.txt", FileMode.Append);

How about flushing also before creating the second file stream

try my exception logger it has the code you need…
http://wiki.tinyclr.com/images/1/19/Exception_Logger.zip

here is a piece of it:


private readonly ArrayList _queuedMessages = new ArrayList();
//add the error to our internal log
                _queuedMessages.Add("testing......");
FileName = @ "\USB\BugReport.txt" ;

 lock (this) // locking the file so no other function tries opening the file while still writing it to it.
                {
                    using (var stream = new FileStream(FileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)
                        )
                    using (TextWriter writer = new StreamWriter(stream))
                    {
                        foreach (var queuedMessage in _queuedMessages)
                        {
                            writer.WriteLine(queuedMessage);
                        }
                        writer.Flush();
                        _queuedMessages.Clear();// clear the internal log since we have written it to the file.
                    }
                }

[quote]try my exception logger it has the code you need…
http://wiki.tinyclr.com/images/1/19/Exception_Logger.zip[/quote]

He didn’t found it because it is not on codeshare…hint hint add to codeshare :slight_smile:

1 Like

Hi Gus,
Codeshare wasn’t available at the time, it was disabled. so i uploaded it to the wiki to not lose the code…
i’ll see if i can move it there…
thanks.

i tried a bunch of variations based on the last (JAYJAY) post…none seem to work…in this last try , I tried the stream with both a direct string (see below )& also tried using data1 & data instead of the direct strings…all just give Garbage.

how can you simply add a few extra strings to a file (will eventually do it in a loop)?

 // Assume one storage device is available, 
                // access it through NETMF
                string rootDirectory = VolumeInfo.GetVolumes()[0].RootDirectory;
                FileStream FileHandle = new FileStream(rootDirectory + @ "\hellome1.txt", FileMode.Create);
                byte[] data = Encoding.UTF8.GetBytes("four score and");
                byte[] data1 = Encoding.UTF8.GetBytes(" seven hundred years ago");

                TextWriter writer = new StreamWriter(FileHandle);
                writer.WriteLine("this is a test");
                writer.WriteLine("this is the next section of text");
                writer.WriteLine("last but not least");
                // write the data and close the file
                writer.Flush();
                FileHandle.Close();
                FileHandle.Dispose();
               
              
                VolumeInfo.GetVolumes()[0].FlushAll();
                // if we need to unmount
                ps.UnmountFileSystem();

i get:
°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóô

One good thing to do usually is to run similar code in emulator to see what output you will get. I am not sure if this applies to file system code but it is not a bad idea to try.

[quote]One good thing to do usually is to run similar code in emulator to see what output you will get. I am not sure if this applies to file system code but it is not a bad idea to try.
[/quote]

since this is to write on a mem stick & is a complex operation, i’m not sure if that would show anything, or how it would relate to the file system operations…In any case does anyone really know how to do this?

Write one string
then add another
then add another

JAYJAY:
I tried your code as follows, but it fails, creates the file (bugreport, which was not present) and gives:

“four score andrst message! file! ¡¢£¤¥¦§¨©ª«¬­®¯°±”

…but interestingly none of this text is from this program version…it creates the file (there was no debugreport file), but some old text from elsewhere?appears & none of the text from this run is included…the code must be running, since it creates the proper file name

Can you try this on your system & see if you get the same result?

        static void DeviceConnectedEvent(USBH_Device device)
        {
            if (device.TYPE == USBH_DeviceType.MassStorage)
            {
                Debug.Print("USB Mass Storage detected...");
                ps = new PersistentStorage(device);
                ps.MountFileSystem();
               

            }
        }
 
        static void RemovableMedia_Insert(object sender, MediaEventArgs e)
        {
            Debug.Print("Storage \"" + e.Volume.RootDirectory + 
                        "\" is inserted.");
            Debug.Print("Getting files and folders:");
            if (e.Volume.IsFormatted)
            {
                string[] files = Directory.GetFiles(e.Volume.RootDirectory);
                string[] folders = 
                           Directory.GetDirectories(e.Volume.RootDirectory);
 
                Debug.Print("Files available on " + 
                            e.Volume.RootDirectory + ":");
                for (int i = 0; i < files.Length; i++)
                    Debug.Print(files[i]);
 
                Debug.Print("Folders available on " + 
                            e.Volume.RootDirectory + ":");
                for (int i = 0; i < folders.Length; i++)
                    Debug.Print(folders[i]);
                Thread.Sleep(1111);

                 ArrayList _queuedMessages = new ArrayList();
                    //add the error to our internal log
                _queuedMessages.Add("testing......");
                _queuedMessages.Add("wow this works");    // these should appear in the file...but do not
                _queuedMessages.Add("FULL STEAM AHEAD!");
                string FileName = @ "\USB\BugReport.txt" ;

                {
                    using (var stream = new FileStream(FileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)
                        )
                    using (TextWriter writer = new StreamWriter(stream))
                    {
                        foreach (var queuedMessage in _queuedMessages)
                        {
                            writer.WriteLine(queuedMessage);
                        }
                        writer.Flush();
                        _queuedMessages.Clear();// clear the internal log since we have written it to the file.
                    }
                }
                ps.UnmountFileSystem();

What board are you using?

Yes Eric is correct, knowing the type of board you’re using would help…

i also recommend you download my Exception logger and use it as is, assuming you have a Gadgeteer compatible board… if not please start a new project and include only the code mentioned earlier…

Let us know.

To see this problem, we want to know what kind of board are you using ?

It is a cobra board (EMX).

I used the part of Jay-Jay’s cosde that should do the trick, I think…but it did not

Did you tried another USB stick?