1

I have the following code to read a line from a text file. In the UpdateFile() method I need to delete the existing one line and update it with a new line. Can anybody please provide any ideas? Thank you.

FileInfo JFile = new FileInfo(@"C:\test.txt");
            using (FileStream JStream = JFile.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
            {
                int n = GetNUmber(JStream);
                n = n + 1;
        UpdateFile(JStream);

            }

private int GetNUmber(FileStream jstream)
        {
            StreamReader sr = new StreamReader(jstream);
            string line = sr.ReadToEnd().Trim();
            int result;
            if (string.IsNullOrEmpty(line))
            {
                return 0;
            }
            else
            {
                int.TryParse(line, out result);
                return result;
            }
        }

private int UpdateFile(FileStream jstream)
{
    jstream.Seek(0, SeekOrigin.Begin);
    StreamWriter writer = new StreamWriter(jstream);
    writer.WriteLine(n);
}
Jyina
  • 2,530
  • 9
  • 42
  • 80

3 Answers3

3

I think the below code can do your job

StreamWriter writer = new StreamWriter("file path", false); //false means do not append
writer.Write("your new line");
writer.Close();
Ghyath Serhal
  • 7,466
  • 6
  • 44
  • 60
  • In my case, I am not able to use the file path as I have the file opened using a stream within "using" block. I got an error message "The process cannot access the file because it is being used by another process". Thanks. – Jyina May 06 '11 at 14:25
  • pass the stream in the constructor of the StreamWriter StreamWriter writer = new StreamWriter(youstream); – Ghyath Serhal May 07 '11 at 06:14
2

If you're just writing a single line, there's no need for streams or buffers or any of that. Just write it directly.

using System.IO;

File.WriteAllText(@"C:\test.txt", "hello world");
recursive
  • 83,943
  • 34
  • 151
  • 241
2
var line = File.ReadLines(@"c:\temp\hello.txt").ToList()[0];
var number = Convert.ToInt32(line);
number++;
File.WriteAllText(@"c:\temp\hello.txt", number.ToString());

Manage the possible exceptions, file exists, file has lines, the cast......

jjchiw
  • 4,375
  • 1
  • 29
  • 30
  • Is there any way we can manage using streams. In my case I need to lock the file so that the file can be accessed by only one user at a time. So I tried to create a stream with FileShare.None option and "using" block. – Jyina May 06 '11 at 14:21
  • Interesting I didn't know this http://www.dotnetperls.com/file-readlines the difference between File.ReadLines and File.ReadAllLines and this seems like the question http://stackoverflow.com/questions/5338450/file-readlines-without-locking-it – jjchiw May 06 '11 at 14:41
  • Thanks for sharing the information. In my case, I need to lock the file in read and write modes so I think FileShare.None best suits my requirement. – Jyina May 06 '11 at 15:02