• Status: Solved
• Priority: Medium
• Security: Public
• Views: 328

# editing with text file c#

hi,

I want to read text file (which has some value written in one line for example "55")  in c#

now after reading, I want to check the value if its equal to 55 I want to clear this value and store new value (for example "66") and save the file with new value (where 55 is replaces with 66)

0
Ameerh24
2 Solutions

Commented:

string fileValue;
using (var sr = new StreamReader("c:\\text.txt"))
{
sr.Close();
}

if (fileValue.Equals("55"))
fileValue = "66";

using (var sw = new StreamWriter("c:\\text.txt", false))
{
sw.Write(fileValue);
sw.Close();
}

0

Commented:
Hi,

you will have to use the StreamReader and StreamWriter classes. Check them out on MSDN.

gsx1022
0

Commented:
public static void ReadTextFile()
{
string sFrom = "", sTo = "";
string sBuffer = "";
try
{
Console.WriteLine("Enter name of teh file with full path");
Console.WriteLine("Enter the name of the file for the output");

StreamWriter writer = new StreamWriter(sTo);

if (int.Parse(sBuffer) == 55)
{
writer.Write(66);

}
}
catch (FileNotFoundException fnf)
{
}
catch (Exception e)
{
Console.WriteLine("An error occured. {0}", e);
}
}

0

Commented:
Just want to mention that if you happened to use VS2005, change this line:
using (var sw = new StreamWriter("c:\\text.txt", false))
to this:
using (StreamWriter sw = new StreamWriter("c:\\text.txt", false))

You can also get the int value by this:

I think zadeveloper did a good job helping you. Happy Coding!
0

Commented:
All of these solutions assume that your text file only contains one line of text. Is that the case, or does your file have multiple lines of text?
0

Commented:
read all the text from your file with File.ReadAllText method, loop into all lines of file and just call string.replace("55","66").
HTH
0

Commented:
0

Commented:
And of course, that would depend on how big your file is. I imagine you'd have a tough time processing a 4 GB text file if you called ReadToEnd().

;)
0

Commented:
This is true, but from the description of the problem give it would seem like a 1 line file. I would not use any suggestion on this page to open a 4gb text file. :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.