Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Saving to Text file question


  • Please log in to reply
6 replies to this topic

#1 X_Programmer

X_Programmer

    CC Regular

  • Just Joined
  • PipPipPip
  • 47 posts

Posted 26 August 2010 - 02:50 PM

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
  • 0

#2 PsychoCoder

PsychoCoder

    CC Resident

  • Just Joined
  • PipPipPipPip
  • 89 posts

Posted 26 August 2010 - 03:19 PM

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 :)
  • 0
SELECT * FROM Users WHERE Clue > 0;
ERROR: 0 results returned
Posted Image

#3 X_Programmer

X_Programmer

    CC Regular

  • Just Joined
  • PipPipPip
  • 47 posts

Posted 26 August 2010 - 03:55 PM

Alright, I'll try that out, thanks :)
  • 0

#4 cdg10620

cdg10620

    CC Addict

  • Senior Member
  • PipPipPipPipPip
  • 344 posts
  • Programming Language:C#, JavaScript, PL/SQL, Transact-SQL, VBScript, Others

Posted 27 August 2010 - 05:29 AM

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

#5 kepp

kepp

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts

Posted 27 August 2010 - 08:36 AM

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)
  • 0

#6 zoranh

zoranh

    CC Addict

  • Just Joined
  • PipPipPipPipPip
  • 187 posts

Posted 30 August 2010 - 01:10 AM

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.
  • 0

#7 X_Programmer

X_Programmer

    CC Regular

  • Just Joined
  • PipPipPip
  • 47 posts

Posted 30 August 2010 - 11:13 AM

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.

  • 0




Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download