I need to check if the string exists in a text file and if it does then proceed. if not, it will display a MessageBox saying that the ID does not exist.
In my previous question, I tried to check if "testfile.txt" contains the string inputted by the user in TextBox1 then copy the line which contains the string into a new textfile. Using the approach that has been suggested, here's a snippet of what I have so far:
string emp_profile = #"EmployeeData.txt"; //file to be checked
string endata = #"EndData.txt"; //terminated employees data file
string end_tdata = #"end_tdata.txt"; //holds sample's data
//validates if eid exists and if it exists copies data of sample
//plus txt_end.Text into temporary data file
string[] dataline = File.ReadAllLines(emp_profile);
using (StreamWriter w = File.AppendText(end_tdata))
{
foreach (var line in dataline)
{
if (line.Contains(txt_un.Text))
{
w.WriteLine(txt_end.Text + "," + line);
w.Close();
}
}
}
string end_holddata = #"end_holddata.txt";
//read original file
string[] raw_data = File.ReadAllLines(endata);
using (StreamWriter r = File.AppendText(end_holddata))
{
foreach (var line in raw_data)
{
if (!line.Contains(txt_un.Text))
r.WriteLine(line);
}
r.Close();
}
//delete original file
File.Delete(endata);
//creates new data file with old data path
//and copies the temporary data held testdata
using (Stream input = File.OpenRead(end_holddata))
using (Stream output = new FileStream(endata, FileMode.Append,
FileAccess.Write, FileShare.None))
{
input.CopyTo(output);
}
//appends new data of sample into the newly created data file
using (Stream input = File.OpenRead(end_tdata))
using (Stream output = new FileStream(endata, FileMode.Append,
FileAccess.Write, FileShare.None))
{
input.CopyTo(output);
}
DialogResult result = MessageBox.Show("Data has been recorded.");
//clears all temporary files
if (result == DialogResult.OK)
{
File.Delete(end_holddata);
File.Delete(end_tdata);
}
What I'm trying to do here is that I'm copying the data from the "emp_profile.txt that does not contain the txt_un.Text into "end_holddata" and copy the line that contains the input into a different file end_tdata.txt, delete the old datafile to clear contents then merge the data into a new data with the same pathfile as the old one. Afterwards, the temporary data files would be deleted.
I tried enclosing the above snippet within this but it's not working the way I want it to.
string[] dataline = File.ReadAllLines(emp_profile);
for (int i = 0; i < dataline.Length; i++)
{
if (dataline[i].Contains(txt_un.Text))
{
//code snippet here
}
else
MessageBox.Show("ID does not exist!");
}
Any help would appreciated! Thank you in advance!
Related
I've got a windows service that I have to modify. Current code is this:
public IRecord2 GetRecord(string name)
{
string path = Path.Combine(this.DirectoryPath, name);
if (!File.Exists(path))
return null;
byte[] contents;
lock (locker) {
using(FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, bufferSize:4096, useAsync:true)) //WHERE THE PROBLEM IS OCCURRING
{
using (BinaryReader br = new BinaryReader(fs))
{
contents = br.ReadBytes((int)fs.Length);
br.Close(); //unnecessary but threw it in just to be sure
fs.Close(); //unnecessary but threw it in just to be sure
}
}
}
return new Record2()
{
Name = name,
Contents = contents
};
}
Code that calls the function:
public void Process(string pickupFileName)
{
string uniqueId = DateTime.Now.ToString("(yyyy-MM-dd_HH-mm-ss)");
string exportFileName = Path.GetFileNameWithoutExtension(pickupFileName) + "_" + uniqueId + ".csv";
string archiveFileName = Path.GetFileNameWithoutExtension(pickupFileName) + "_" + uniqueId + Path.GetExtension(pickupFileName);
string unprocessedFileName = Path.GetFileNameWithoutExtension(pickupFileName) + "_" + uniqueId + Path.GetExtension(pickupFileName);
try
{
_logger.LogInfo(String.Format("Processing lockbox file '{0}'", pickupFileName));
IRecord2 record = _pickup.GetRecord(pickupFileName);
if (record == null)
return;
_archive.AddOrUpdate(new Record2() { Name = archiveFileName, Contents = record.Contents });
string pickupFileContents = UTF8Encoding.UTF8.GetString(record.Contents);
IBai2Document document = Bai2Document.CreateFromString(pickupFileContents);
StringBuilder sb = Export(document);
_export.AddOrUpdate(new Record2() { Name = exportFileName, Contents = Encoding.ASCII.GetBytes(sb.ToString()) });
_pickup.Delete(pickupFileName);
}
catch(Exception ex)
{
throw ex;
}
}
Function that calls Process:
public void Process()
{
foreach (ConfigFolderPath configFolderPath in _configSettings.ConfigFolderPaths)
{
IRecordRepository pickup = new FileRepository(configFolderPath.PickupFolderPath);
IRecordRepository export = new FileRepository(configFolderPath.ExportFolderPath);
IRecordRepository archive = new FileRepository(configFolderPath.ArchiveFolderPath);
IRecordRepository unprocessed = new FileRepository(configFolderPath.UnprocessedFolderPath);
Converter converter = new Converter(Logger,pickup, export, archive, unprocessed);
foreach (string fileName in pickup.GetNames())
{
if (_configSettings.SupportedFileExtensions.Count > 0 && !_configSettings.SupportedFileExtensions.Any(extension => extension.ToLower() == Path.GetExtension(fileName).ToLower()))
continue;
Action action = () => converter.Process(fileName);
_queue.TryEnqueue(action, new WorkTicket() { Description = String.Format("Processing '{0}'", fileName), SequentialExecutionGroup = fileName });
}
}
}
When 1 file is sent to the service, it processes and reads the file correctly. However, if two files are sent (difference of 3 minutes), the first file will process correctly, but the second will give me "System.IO.IOException: The process cannot access the file "filename" because it is being used by another process.
Is the solution to use a mutex as per https://stackoverflow.com/a/29941548/4263285 or is there a better solution to solve this?
Edit: More context:
Service is constantly running - as soon as files are dropped into a folder, it begins the process.
get the file data (function up above)
take the data, transform it, and put it into a different file
Delete the original file from the one up above
rinse and repeat if more files
if one file is placed in the folder, it works correctly.
if two files are placed in the folder, it breaks on the second file
if service is stopped and restarted, it works again
In your code add ".Close()" here, at the end of the line :
using(FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, bufferSize:4096, useAsync:true).Close())
I have a program in which a user can set up a bank account. It writes (in order) name, address, balance, and account type to a base text file. I am trying to provide a function for the user to be able to update their account by providing a new name and address. The balance and account type cannot be edited, and are taken from the base file.
The program currently writes the new data to a temporary file, which will eventually overwrite the base file with its contents. However, it also writes the old data from the user to the file, which is not what I want. Currently, the file will contain both the old data (before the user went to change it) and the new data (what the user entered to update).
I would like some help on how I can overwrite or skip the old data in the temporary file, and leave only the new data and other accounts.
I have tried to implement this feature by using the String.Replace method, iterating it for each data item by using a for loop (I use a for loop to show the user's data if they select the option to view their data, which works for that), but it did not function as intended (it did not replace the text or do anything).
else if (ChoiceInput == "3")
//Choice 3 - Update account details.
{
//Check that the account exists.
using (FileStream fs2 = new FileStream(FileName, FileMode.Open, FileAccess.ReadWrite))
{
StreamReader sr2 = new StreamReader(fs2);
StreamWriter sw2 = new StreamWriter(fs2);
Console.Write("Enter the account name: ");
string NameCheck = Console.ReadLine();
string NameValidation;
try
{
NameValidation = sr2.ReadLine();
string NameReplace = NameValidation;
NameReplace.Replace(NameValidation, "");
sw2.Write(NameReplace);
while (NameValidation != null)
{
if (NameValidation.Contains(NameCheck))
//Account exists.
{
for (int i = 0; i < 3; i++)
{
if (i == 1)
{
string ReadReplace = sr2.ReadLine();
ReadReplace.Replace(ReadReplace, "" + "\r\n");
sw2.Write(NameReplace);
Console.WriteLine(ReadReplace);
}
else if (i == 2)
{
string ReadReplace = sr2.ReadLine();
ReadReplace.Replace(ReadReplace, "" + "\r\n");
sw2.Write(NameReplace);
Console.WriteLine(ReadReplace);
}
}
}
using (StreamWriter sw = new StreamWriter(FileNameTemp, true))
{
//Enter new details. It writes these details to the temporary file.
Console.WriteLine("Account found.");
Console.WriteLine("Enter new name: ");
string AccountName = Console.ReadLine();
sw.WriteLine(AccountName);
Console.WriteLine("Enter new address: ");
string AccountAddress = Console.ReadLine();
sw.WriteLine(AccountAddress);
NameValidation = null;
for (int i = 0; i < 3; i++)
//Loop that iterates twice, writing the balance and account type to the temporary file. This data cannot be changed.
{
string Write = sr2.ReadLine();
if (i == 1)
//Balance.
{
sw.WriteLine(Write);
}
else if (i == 2)
//Account type.
{
sw.WriteLine(Write);
}
}
}
using (StreamReader sre = new StreamReader(FileName, true))
{
using (StreamWriter sw = new StreamWriter(FileNameTemp, true))
{
string Lines;
int Counter = 0;
while ((Lines = sre.ReadLine()) != null)
//While the program still has lines to go through, it will continue writing to the text file.
{
Console.WriteLine(Lines);
sw.Write(Lines + "\r\n");
Counter++;
}
}
using (FileStream fs = new FileStream(FileNameTemp, FileMode.Truncate))
//Clears the temporary file, as not doing so would cause issues.
{
}
Console.WriteLine("Account details updated!");
}
}
}
finally
{
Console.ReadLine();
}
}
}
Update: I have added an example of what I am trying to do. The first for loop under NameValidation is supposed to remove the old details on the base file by replacing them with empty strings. However, it does not work as intended. It does not write anything to the base file, and then it crashes with the error "System.IO.IOException: 'The process cannot access the file 'C:\program1\Bank.txt' because it is being used by another process.'", when it carries onto StreamReader sre.
However, it does write the balance and account type of the next account into the temporary file.
Okay. Some tips on how to proceed.
This is how your text file should be
Id, Name, address, Balance
1, testName, xyz, 300
Before Insert check if the name already exists. If yes, get the id (here if testname exists, we have to get the id value i.e 1).
If we get this id, we can parse the file and update them with StreamWriter
[Or]
Read the name and address, replace with string.replace
I have a text file containing some information that I want to edit. The file looks something like this:
id: 31
name: Anna
profession: Doctor
I can read that entry with a StreamReader, and present it in my application. I then want the user to be able to change the name and profession of an entry, so I'd like to edit these specific rows to the new values, while keeping id intact (in my real code, there's not just a few rows, but a lot of rows where only some should be changed). So, for example, I want the file, at the end of my operation, to look like this.
id: 31
name: Emma
profession: Programmer
However, I also have to take into account that sometimes the rows don't exist beforehand. For example, before editing Anna to Emma, it's not certain that she had a profession, the file could have looked like this:
id: 31
name: Anna
And in that case, I want to add the line profession: Programmerto the end there.
I tried using a FileStreamwith ReadWrite access, that I give to a StreamReader and a StreamWriter, but then I found no way of changing or replacing a line of text, only reading it and writing a new identical line while keeping the old.
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite))
using (StreamReader reader = new StreamReader(fileStream))
using (StreamWriter writer = new StreamWriter(fileStream))
{
bool idExists = false;
bool nameExists = false;
bool tagsExist = false;
string line;
while((line = reader.ReadLine()) != null)
{
if (line.StartsWith("id:"))
idExists = true;
else if (line.StartsWith("name:"))
{
nameExists = true;
line = $"name: {entryToSave.Name}";
writer.WriteLine(line); // Will write an additional line and not replace
}
else if (line.StartsWith("profession:"))
{
professionExists = true;
line = $"profession: {entryToSave.Profession}";
writer.WriteLine(line); // Will write an additional line and not replace
}
}
if (!idExists)
writer.WriteLine($"id: {generatedId}");
if (!nameExists)
writer.WriteLine($"name: {entryToSave.Name}");
if (!professionExists)
writer.WriteLine($"profession: {entryToSave.Profession}");
}
I also tried using File.ReadAllLines, loop through the lines, and then write back all the lines to the file, only modifying the lines that were to be modified. However, I don't have access to the file through File.WriteAllLines for some reason that I don't understand, as a StreamWriter has access. Code:
var previousData = File.ReadAllLines(filePath);
var newData = new List<string>();
bool idExists = false;
bool nameExists = false;
bool professionExists = false;
for (int i = 0; i < previousData.Length; i++)
{
var line = previousData[i];
if (line.StartsWith("id:")
idExists = true;
else if (line.StartsWith("name:")
{
nameExists = true;
line = $"name: {entryToSave.Name}";
}
else if (line.StartsWith("profession:"))
{
professionExists = true;
line = $"profession: {entryToSave.Profession}";
}
newData.Add(line);
}
if (!idExists)
newData.Add($"id: {generatedId}");
if (!nameExists)
newData.Add($"name: {entryToSave.Name}");
if (!professionExists)
newData.Add($"profession: {entryToSave.Profession}");
File.WriteAllLines(filePath, newData.ToArray()); // Access denied
How is this most easily achieved, without file streams interfering with each other?
If you've already presented the data to the user in entries, enabling the user to edit name and profession, you could just read the file, get the ID and fill the remainder of the file with the value of the entries. The following is an example console application.
static void Main(string[] args)
{
var filePath = "test.txt";
// Simulated input from user
// these should come from entries in the application?
var name = "Foo";
var profession = "Bar";
var personData = new PersonData(); // class declared below
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite))
using (StreamReader reader = new StreamReader(fileStream))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (line.StartsWith("id:"))
personData.ID = line;
}
} // Now reader and filestream is closed, file is available again.
// You don't specify what you would like to happen if personData.ID is null,
// so I make an assumption the generatedId is what you'd like to use.
if (string.IsNullOrWhiteSpace(personData.ID)
personData.ID = $"id: {generatedId}";
// Add the data from the entries
personData.Name = $"name: {name}";
personData.Profession = $"profession: {profession}";
File.Delete(filePath); // remove the file
using (FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
using (StreamWriter writer = new StreamWriter(fileStream))
{
writer.WriteLine(personData.ID);
writer.WriteLine(personData.Name);
writer.WriteLine(personData.Profession);
}
}
private class PersonData
{
public string ID { get; set; }
public string Name { get; set; }
public string Profession { get; set; }
}
Now you just have to find out how to get access to the file if you're having permission problems.
I have two methods: saveFile and saveAsToFile. The first one is supposed to overwrite the contents of the current, existing file. While the second is supposed to save as a new file (if the current is non-existing or the user just wants to make a copy.)
When I use the saveAsToFile method it works every time. When I use the saveFile method it doesn't write anything. (I DO see the "Saved!" MessageBox, though.)
Here are my methods:
public void saveFile(string[] inData, string inDataTitle)
{
//This method saves the file
SaveFileDialog savefile;
string trueFileName;
if (isStrArrayNotEmpty(inData)) {
//Only attempt to save the file if there is anything written in the textArea
if (f.getDocumentSavedStatus()) {
if (f.getDocumentChangedStatus()) {
savefile = new SaveFileDialog();
if (inDataTitle.EndsWith("*")) {
//Remove the asterisk from the document name
savefile.FileName = inDataTitle.Substring(0, inDataTitle.Length - 1);
}
else {
savefile.FileName = inDataTitle;
}
StreamWriter sw = new StreamWriter(savefile.FileName, false);
foreach (string line in inData) {
sw.WriteLine(line);
}
sw.Flush();
if (sw.BaseStream != null)
sw.BaseStream.Flush();
sw.Close();
/*
using (StreamWriter sw = new StreamWriter(savefile.FileName, false))
foreach (string line in inData) {
sw.WriteLine(line);
}
*/
f.setDocumentName(string.Empty);
trueFileName = Path.GetFileName(savefile.FileName);
f.setDocumentName(trueFileName);
f.setDocumentSavedStatus(true);
f.setDocumentChangedStatus(false); //Changes saved, status updated
MessageBox.Show("Saved!");
}
}
else {
//If the document hasn't been saved before, send the values to the 'Save As' method
saveAsToFile(inData, inDataTitle);
}
}
}
public void saveAsToFile(string[] inData, string inDataTitle)
{
//This method checks if there is anything written in the texArea,
//if so it prompts the user to save the file to disk (Save As)
SaveFileDialog savefile;
string trueFileName;
if (isStrArrayNotEmpty(inData)) {
//Only attempt to save the file if there is anything written in the textArea
savefile = new SaveFileDialog();
if (inDataTitle.EndsWith("*")) {
//Remove the asterisk from the document name
savefile.FileName = inDataTitle.Substring(0, inDataTitle.Length - 1);
}
else {
savefile.FileName = inDataTitle;
}
savefile.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
if (savefile.ShowDialog() == DialogResult.OK) {
StreamWriter sw = new StreamWriter(savefile.FileName, false);
foreach (string line in inData) {
sw.WriteLine(line);
}
sw.Flush();
if (sw.BaseStream != null)
sw.BaseStream.Flush();
sw.Close();
/*
using (StreamWriter sw = new StreamWriter(savefile.FileName))
foreach (string line in inData) {
sw.WriteLine(line);
}
*/
f.setDocumentName(string.Empty);
trueFileName = Path.GetFileName(savefile.FileName);
f.setDocumentName(trueFileName);
f.setDocumentSavedStatus(true);
f.setDocumentChangedStatus(false); //Changes saved, status updated
}
}
}
As you can see by the comments in the code; I tried using using, and then I tried to "manually flush" the streamwriter, but nothing works.
Using saveAsToFile works every time. It overwrites the text file as expected, no problems. While saveFile doesn't write anything to the file. (Leaving it unchanged.)
I tried looking for errors in saveFile by using MessageBox.Show to print the values of savefile.Filename and line in the appropriate places - they all worked as expected, yet nothing is written to the actual text file.
isStrArrayNotEmpty returns true if the string array does not contain any white spaces.
getDocumentSavedStatus returns the value of a boolean which tells if the file has been saved before or not (existent / non-existent)
getDocumentChangedStatus returns the value of a boolean which tells if the file has been modified or not (asterisk by the end of the file name, indicating that work will be lost if the user shuts down the application.)
Does the inDataTitle parameter include the path of the filename you're trying to save? If not, it's likely saving to a file of the same name but in a different folder.
After your line:-
StreamWriter sw = new StreamWriter(savefile.FileName, false);
add the line:-
MessageBox.Show(((FileStream)(sw.BaseStream)).Name);
and it'll tell you where the file is being saved.
Try replacing
StreamWriter sw = new StreamWriter(savefile.FileName, false);
foreach (string line in inData) {
sw.WriteLine(line);
}
sw.Flush();
if (sw.BaseStream != null)
sw.BaseStream.Flush();
sw.Close();
with
File.WriteAllLines(saveFile.Filename, inData);
I have two text files, Source.txt and Target.txt. The source will never be modified and contain N lines of text. So, I want to delete a specific line of text in Target.txt, and replace by an specific line of text from Source.txt, I know what number of line I need, actually is the line number 2, both files.
I haven something like this:
string line = string.Empty;
int line_number = 1;
int line_to_edit = 2;
using StreamReader reader = new StreamReader(#"C:\target.xml");
using StreamWriter writer = new StreamWriter(#"C:\target.xml");
while ((line = reader.ReadLine()) != null)
{
if (line_number == line_to_edit)
writer.WriteLine(line);
line_number++;
}
But when I open the Writer, the target file get erased, it writes the lines, but, when opened, the target file only contains the copied lines, the rest get lost.
What can I do?
the easiest way is :
static void lineChanger(string newText, string fileName, int line_to_edit)
{
string[] arrLine = File.ReadAllLines(fileName);
arrLine[line_to_edit - 1] = newText;
File.WriteAllLines(fileName, arrLine);
}
usage :
lineChanger("new content for this line" , "sample.text" , 34);
You can't rewrite a line without rewriting the entire file (unless the lines happen to be the same length). If your files are small then reading the entire target file into memory and then writing it out again might make sense. You can do that like this:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
int line_to_edit = 2; // Warning: 1-based indexing!
string sourceFile = "source.txt";
string destinationFile = "target.txt";
// Read the appropriate line from the file.
string lineToWrite = null;
using (StreamReader reader = new StreamReader(sourceFile))
{
for (int i = 1; i <= line_to_edit; ++i)
lineToWrite = reader.ReadLine();
}
if (lineToWrite == null)
throw new InvalidDataException("Line does not exist in " + sourceFile);
// Read the old file.
string[] lines = File.ReadAllLines(destinationFile);
// Write the new file over the old file.
using (StreamWriter writer = new StreamWriter(destinationFile))
{
for (int currentLine = 1; currentLine <= lines.Length; ++currentLine)
{
if (currentLine == line_to_edit)
{
writer.WriteLine(lineToWrite);
}
else
{
writer.WriteLine(lines[currentLine - 1]);
}
}
}
}
}
If your files are large it would be better to create a new file so that you can read streaming from one file while you write to the other. This means that you don't need to have the whole file in memory at once. You can do that like this:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
int line_to_edit = 2;
string sourceFile = "source.txt";
string destinationFile = "target.txt";
string tempFile = "target2.txt";
// Read the appropriate line from the file.
string lineToWrite = null;
using (StreamReader reader = new StreamReader(sourceFile))
{
for (int i = 1; i <= line_to_edit; ++i)
lineToWrite = reader.ReadLine();
}
if (lineToWrite == null)
throw new InvalidDataException("Line does not exist in " + sourceFile);
// Read from the target file and write to a new file.
int line_number = 1;
string line = null;
using (StreamReader reader = new StreamReader(destinationFile))
using (StreamWriter writer = new StreamWriter(tempFile))
{
while ((line = reader.ReadLine()) != null)
{
if (line_number == line_to_edit)
{
writer.WriteLine(lineToWrite);
}
else
{
writer.WriteLine(line);
}
line_number++;
}
}
// TODO: Delete the old file and replace it with the new file here.
}
}
You can afterwards move the file once you are sure that the write operation has succeeded (no excecption was thrown and the writer is closed).
Note that in both cases it is a bit confusing that you are using 1-based indexing for your line numbers. It might make more sense in your code to use 0-based indexing. You can have 1-based index in your user interface to your program if you wish, but convert it to a 0-indexed before sending it further.
Also, a disadvantage of directly overwriting the old file with the new file is that if it fails halfway through then you might permanently lose whatever data wasn't written. By writing to a third file first you only delete the original data after you are sure that you have another (corrected) copy of it, so you can recover the data if the computer crashes halfway through.
A final remark: I noticed that your files had an xml extension. You might want to consider if it makes more sense for you to use an XML parser to modify the contents of the files instead of replacing specific lines.
When you create a StreamWriter it always create a file from scratch, you will have to create a third file and copy from target and replace what you need, and then replace the old one.
But as I can see what you need is XML manipulation, you might want to use XmlDocument and modify your file using Xpath.
You need to Open the output file for write access rather than using a new StreamReader, which always overwrites the output file.
StreamWriter stm = null;
fi = new FileInfo(#"C:\target.xml");
if (fi.Exists)
stm = fi.OpenWrite();
Of course, you will still have to seek to the correct line in the output file, which will be hard since you can't read from it, so unless you already KNOW the byte offset to seek to, you probably really want read/write access.
FileStream stm = fi.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
with this stream, you can read until you get to the point where you want to make changes, then write. Keep in mind that you are writing bytes, not lines, so to overwrite a line you will need to write the same number of characters as the line you want to change.
I guess the below should work (instead of the writer part from your example). I'm unfortunately with no build environment so It's from memory but I hope it helps
using (var fs = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite)))
{
var destinationReader = StreamReader(fs);
var writer = StreamWriter(fs);
while ((line = reader.ReadLine()) != null)
{
if (line_number == line_to_edit)
{
writer.WriteLine(lineToWrite);
}
else
{
destinationReader .ReadLine();
}
line_number++;
}
}
The solution works fine. But I need to change single-line text when the same text is in multiple places. For this, need to define a trackText to start finding after that text and finally change oldText with newText.
private int FindLineNumber(string fileName, string trackText, string oldText, string newText)
{
int lineNumber = 0;
string[] textLine = System.IO.File.ReadAllLines(fileName);
for (int i = 0; i< textLine.Length;i++)
{
if (textLine[i].Contains(trackText)) //start finding matching text after.
traced = true;
if (traced)
if (textLine[i].Contains(oldText)) // Match text
{
textLine[i] = newText; // replace text with new one.
traced = false;
System.IO.File.WriteAllLines(fileName, textLine);
lineNumber = i;
break; //go out from loop
}
}
return lineNumber
}