Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Tuesday, September 13, 2005 4:23 AM
is there any functions/methods to append text lines (2 lines)
in the first line of .txt files
ex:
i got a txt files contains 3 lines
and i want to append 2 lines above the first line
All replies (7)
Tuesday, September 13, 2005 4:51 AM âś…Answered
No, to do this you need to read the file, put your text in front, and overwrite the entire file.
Tuesday, September 13, 2005 6:11 AM
I think the easiest way is to read the File using the System.IO.StreamReader and read it into a string and add the initial two lines to the string by concatenation.
Then close the StreamReader and open the file using the StreamWriter with append option set to false(which would overwrite the file) and write the string to file.
Sample code snippet:
string strFileContents = "";
string strDataToAppend = "This is the initial data to append";
StreamReader srReader = null;
StreamWriter swWriter = null;
try
{
srReader = new StreamReader(@"C:\SampleText.txt");
strFileContents = srReader.ReadToEnd();
srReader.Close();
strFileContents = strDataToAppend + Environment.NewLine + strFileContents;
swWriter = new StreamWriter(@"C:\SampleText.txt", false);
swWriter.Write(strFileContents);
swWriter.Flush();
}
catch(Exception objException)
{
throw(objException);
}
finally
{
swWriter.Close();
}
Regards,
Vikram
Tuesday, September 13, 2005 6:38 AM
thanks dude....
actually i'm trying not to overwrite the files...that's why ask this
question.
this is my problem
i have a shout box....
its from textarea that read a txt files, i have a textbox and a button
too. each time i click the button, string in the textbox will be added
to the txt files (in the last line). So when i reload the textarea, the
scroll in the textarea always in first position and always show the oldest text,
what i want is neither the scroll automatically scroll down to the last or
i append the string in the first line of the txt files...
since the only methods is to overwrite my txt files, if so
how to scroll my textarea automatically to the last position???
tq in advance
Tuesday, September 13, 2005 9:10 PM
The textbox control has a Select method, you can get the Text property, find it's length, and then select the last position in the text box. I believe that will make it visible.
Wednesday, September 14, 2005 3:00 AM
can u show me some code snippet here?
tq
Wednesday, September 14, 2005 3:09 AM
I missed a step...
textBox1.Select(textBox1.Text.Length, 0);
textBox1.ScrollToCaret();
Saturday, June 3, 2006 5:04 AM
Hey, thanks cgraus. The code snippet was really useful.