File editing without changing structure
I am trying to open and edit a tab delimited file. I need to replace one column header with a token. I am able to open and edit the file, however, the file structure ends up changing.
For example, if I have a file "data.txt" with a column name "Email" on the first line and I want to replace this with a standard token "Your Email"
I can read the line and use a regular expression to replace the column name with the token. Now when I try to write the line back into the same file using the WriteLine method of a streamwriter it overwrites part of the second line of "data.txt"
Is there a way I can go into files and edit parts of it without chainging the file. I know it can be done in Java, but is it possible in C##
I dont want to create a new file, only edit the current file I have
For reference this is what I am doing
sr = new StreamReader(filename);
//create a StreamReader to read file
line = sr.ReadLine();
//read first line of the file
sb = new FileStream(filename, FileMode.OpenOrCreate);
//create a new file stream with Open or Create access
sw = new StreamWriter(sb);
int k = token.Length;
// If you just use the StreamWriter without wrapping it in FileStream you overwrite the file.
// It does not replace the first line. FileMode.OpenOrCreate lets you open the file and write to it.
for(int i=0;i<email.Length - k ;i++)
token = token + " ";
string line1 = Regex.Replace(line, email, token, RegexOptions.Compiled|RegexOptions.Singleline|RegexOptions.IgnoreCase);
//replace occurence of email with desired token case insensitive
//Write to the file
catch (Exception e)