I'm trying to use streamreader to query a .txt file and change a specific line based on a user input. If the line does not exist, I'm trying to append the data to the bottom of the .txt file. So, the user inputs the data into textbox3 and pushes a button. Upon pushing the button, the code will search c:\test.txt to look for a line beginning with the word entered into textbox3. If it finds it, it simply overrides that line with the value the user entered into textbox2. If the current code doesn't find a line beginning with the word entered into textbox3, it copies the entire .txt file and appends it to the bottom of test.txt. However, as stated above, I just want that one line appended to the buttom, not the entire file. As always, thank you for your assistance!
private void button3_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
string line = string.Empty;
// path of the file
using (StreamReader fs = new StreamReader(@"C:\test.txt", true))
{
// checks until end of file
while ((line = fs.ReadLine()) != null)
{
// This will serch a txt file for the word payload
if (line.StartsWith(textBox3.Text))
//This will override the sentence....
sb.AppendLine(textBox3.Text + ", " + textBox2.Text);
else
sb.AppendLine(line);
}
}
// path of file that you want to write,
// and whether you want it to append to the file or not
// I chose not to append.
using (StreamWriter sw = new StreamWriter(@"C:\test.txt", true))
{
sw.Write(sb.ToString());
}
}
}
}
|
Kirtan PatelPosted Oct 31, 2009, 2:55 PM
Writing in Word File is Not same as Writing in TextFile .
you need to use Office Libraries to Write In A Word File :)
ArunPosted Oct 31, 2009, 2:41 PM
Danatas GerviPosted Oct 20, 2009, 3:02 AM
I can guess, what is misunderstanding of author.
He probably forgot about NTFS file system. It seems simple – to add some bytes to real disk, but what to do, if the file is fragmented? Or pervious block is not full yet?
Questions…
:-)
Roei BarPosted Oct 19, 2009, 3:49 PM
Kirtan PatelPosted Oct 19, 2009, 3:44 PM
Here is Complete Code to accomplish task according to you described in above post :)
dont forget to mark "Do you like this answer" if my answer helped you :)
private void button1_Click(object sender, EventArgs e)
{
string Path = @"E:\Test.txt";
string SearchText = textBox1.Text.Trim();
string ReplaceMentString = textBox2.Text.Trim();
string[] Lines = File.ReadAllLines(Path);
bool FoundString = false ;
for (int i = 0; i <= Lines.Length - 1; i++)
{
if (Lines[i].StartsWith(SearchText) == true)
{
//Replace the content With Replace ment String
Lines[i] = ReplaceMentString;
FoundString = true;
break;
}
i++;
}
if (FoundString == false)
{
//Append The Line to End of File
StreamWriter sw = new StreamWriter(Path,true);
sw.WriteLine(textBox2.Text.Trim());
sw.Close();
}
else
{
//Write data back with Replaced String In File
foreach(string line in Lines)
{
StreamWriter sw = new StreamWriter(Path);
sw.WriteLine(line);
}
}
}
Serban CosminPosted Oct 19, 2009, 3:39 PM