Software Development Network>> Visual C#>> How to replace a line in a text file?
You'll have to re-write the whole file. Something like this:
StreamReader r = new StreamReader(filenameIn);
StreamWriter w = new StreamWriter(filenameOut);
try {
string line = string.Empty;
while ((line = r.ReadLine()) != null) {
if (line.Contains("some string")) {
line = "some other string";
}
w.WriteLine(line);
catch (Exception ex) {
// handle exception
finally {
r.Close();
w.Close();
How to replace a line in a text file?
maxal
You'll have to re-write the whole file. Something like this:
StreamReader r = new StreamReader(filenameIn);
StreamWriter w = new StreamWriter(filenameOut);
try {
string line = string.Empty;
while ((line = r.ReadLine()) != null) {
if (line.Contains("some string")) {
line = "some other string";
}
w.WriteLine(line);
}
}
catch (Exception ex) {
// handle exception
}
finally {
r.Close();
w.Close();
}
dreameR.78
using (StreamReader r = new StreamReader(filenameIn))
using (StreamWriter w = new StreamWriter(filenameOut))
{
try
{
for (;;)
{
line = r.ReadLine();
if (line == null)
break;
if (line.Contains("some string"))
{
line = "some other string";
}
w.WriteLine(line);
}
}
catch (Exception ex)
{
// handle exception
}
}