Jump to content

Saving to Text file question

- - - - -

  • Please log in to reply
6 replies to this topic

#1
X_Programmer

X_Programmer

    Learning Programmer

  • Members
  • PipPipPip
  • 89 posts
Hmm...

Recently I've being dealing with an application that saves the current date and a value to a text file over and over again like a log.
I use File.AppendText, but this adds a new line at the bottom of the file, so you have to scroll all the way through the file to find the most recent entry.

I need to find a way to add a string to the TOP of the text file.
I've tried googling it but I can't find a decent answer.

Is there a good way to do this?

Thanks in advance,
X_Programmer

#2
PsychoCoder

PsychoCoder

    Learning Programmer

  • Members
  • PipPipPip
  • 92 posts
Here's one option. You can read the content of your file into a generic list, add your new data to the start of the generic list then write the data back to the file

/// <summary>

/// method for adding new data to the beginning of a file

/// </summary>

/// <param name="file">the file we're adding to</param>

/// <param name="newValue">the value we want to write</param>

private void WriteToStartOfFile(string file,string newValue)

{

    //generic list to hold the contents of the file

    List<string> fileContents = new List<string>();


    //add the content of the file to our list

    fileContents.AddRange(File.ReadAllLines(file));


    //add the new data to the beginning of the list

    fileContents.Insert(0, newValue);  

 

    //now write everything back to the file        

    File.WriteAllLines(file, fileContents.ToArray());


}

The downfall to this is it requires you to read the entire file into memory each time something is added, which can be inefficient with very large files.

Another option you have is:

  • Open a temp file (for writing to)
  • Write the new data to the temp file
  • Open the current file for reading
  • write all the data in the original file to the temp file

Here's an example of that

/// <summary>

/// method for adding new data to the beginning of a file

/// </summary>

/// <param name="file">the file we're adding to</param>

/// <param name="newValue">the value we want to write</param>

private void WriteToStartOfFile(string file, string newValue)

{

    char[] buffer = new char[10000];


    string tempFile = file + ".tmp";

    File.Move(file, tempFile);


    using (StreamReader reader = new StreamReader(tempFile))

    {

        using (StreamWriter writer = new StreamWriter(file, false))

        {

            writer.Write(newValue);


            int totalRead;

            while ((totalRead = reader.Read(buffer, 0, buffer.Length)) > 0)

                writer.Write(buffer, 0, totalRead);

        }


        File.Delete(tempFile);

    }

}

Hope that helps :)
SELECT * FROM Users WHERE Clue > 0;
ERROR: 0 results returned
Posted Image

#3
X_Programmer

X_Programmer

    Learning Programmer

  • Members
  • PipPipPip
  • 89 posts
Alright, I'll try that out, thanks :)

#4
cdg10620

cdg10620

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 389 posts
I typically use the streamwriter method to write text files. It often tends to be quick and painless.
-CDG10620
Software Developer

#5
kepp

kepp

    Newbie

  • Members
  • Pip
  • 2 posts
The most efficient way that i know of is by using the FileStream.Seek() Method
Set the position in the stream to the begining!
Here is something that should get you started: FileStream.Seek Method (System.IO)

#6
zoranh

zoranh

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 207 posts

kepp said:

The most efficient way that i know of is by using the FileStream.Seek() Method
Set the position in the stream to the begining!
Here is something that should get you started: FileStream.Seek Method (System.IO)
That would overwrite existing data at the beginning of the file. The problem here is how to insert data at the beginning of the file and then move everything else further towards the end of the file, so that file eventually increases its size, with new data stored at the beginning.

Any solution to this problem requires the complete file to be re-written, which becomes slower and slower as the file size increases.

One possible solution to this problem is to have a fixed file size, so that old information are not stored in it but rather "forgotten" as they reach the end of the file. Another file could be used to have all data in it, with newest data at the bottom. You certainly do not require very old data in inverse order anyway, because when amount of data becomes very large then it doesn't matter whether they're written top-down or bottom-up - you can't read them.

#7
X_Programmer

X_Programmer

    Learning Programmer

  • Members
  • PipPipPip
  • 89 posts

zoranh said:

That would overwrite existing data at the beginning of the file. The problem here is how to insert data at the beginning of the file and then move everything else further towards the end of the file, so that file eventually increases its size, with new data stored at the beginning.

Any solution to this problem requires the complete file to be re-written, which becomes slower and slower as the file size increases.

One possible solution to this problem is to have a fixed file size, so that old information are not stored in it but rather "forgotten" as they reach the end of the file. Another file could be used to have all data in it, with newest data at the bottom. You certainly do not require very old data in inverse order anyway, because when amount of data becomes very large then it doesn't matter whether they're written top-down or bottom-up - you can't read them.

Your right about the file eventually becoming to big to read efficiently, but even small files are easier to read from top to bottom. So that's why I will just use a temp file and rewrite the whole save file each time I need to add an entry. It's not really efficient, but for now it's all I need.

EDIT: I just got Psycho's Generic List method to work. It's seems a little better than the temp file method.

Edited by X_Programmer, 30 August 2010 - 12:44 PM.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users