I have a file that contains smth like this:
Elsa 12 15
Charlie 3 60
Mattew 4 0
I need to find string, that starts with name and then replace all it line with changed values. I dont know values before search.
So for example I know, that I need to add Mattew 2 to his first value and 4 to second, then file will be like this:
Elsa 12 15
Charlie 3 60
Mattew 6 4
Thanks.
CodePudding user response:
You can use this code to read the file into a Line class (name,firtvalue,secondValue) List , work with it, and after write it again in a file
List Lines = new List();
contentFile.Split("\n").ToList().ForEach(line =>
{
string[] Values = line.Split(" ").ToArray();
Lines.Add(new Line { Name = Values[0], FirstValue = int.Parse(Values[1]), SecondValue = int.Parse(Values[2]) });
});
CodePudding user response:
You can iterate each line of your file using for
loop and find needed one with string.StartsWith()
method. Then, if needed line was found - just rewrite it with provided nameToFind
and new integer values newValue1
and newValue2
, combining them with string.Join()
and " "
whitespace separator.
Example, if you want to set new values to both numbers at line.
static void EditValues(string nameToFind, int newValue1, int newValue2)
{
string file = @"S:\File.txt";
if (File.Exists(file))
{
string[] lines = File.ReadAllLines(file);
for (int i = 0; i < lines.Length; i )
if (lines[i].StartsWith(nameToFind))
{
// Just rewrite line with same name but new values
lines[i] = string.Join(" ", nameToFind, newValue1, newValue2);
// Optionally, if there is no more values to edit - you can break loop immediately
break;
}
// Save (write) lines array back to file.
File.WriteAllLines(file, lines);
}
}
Simplified version with founding index of line with Array.FindIndex
. Note, that if in file is few "Mattew"s - only first would be edited in that case.
static void EditValues(string nameToFind, int newValue1, int newValue2)
{
string[] lines = File.ReadAllLines("File.txt");
int index = Array.FindIndex(lines, line => line.StartsWith(nameToFind));
lines[index] = string.Join(" ", nameToFind, newValue1, newValue2);
File.WriteAllLines("File.txt", lines);
}
If you need to set only one of two numbers in line, you can use some kind of bool
flag (editFirstNumber
in example below) to define first or second number in line should be edited.
To get both numbers you can split line by " "
whitespace separator using string.Split()
method.
Example for editing only one of two numbers:
static void EditValue(string nameToFind, int newValue, bool editFirstNumber)
{
string file = @"S:\File.txt";
if (File.Exists(file))
{
string[] lines = File.ReadAllLines(file);
for (int i = 0; i < lines.Length; i )
if (lines[i].StartsWith(nameToFind))
{
string[] lineValues = lines[i].Split(new char[] { ' ' }, 3, StringSplitOptions.None);
// Parse numbers from line
int.TryParse(lineValues[1], out int number1); // First number
int.TryParse(lineValues[2], out int number2); // Second number
// By boolean flag you can manipulate which one of two numbers to edit
if (editFirstNumber)
number1 = newValue;
else
number2 = newValue;
lines[i] = string.Join(" ", nameToFind, number1, number2);
// Optionally, if there is no more values to edit - you can break loop immediatly
break;
}
File.WriteAllLines(file, lines);
}
}
Then you can just call EditValues("Mattew", 6, 4);
where specify name you want to find and new values for first and second integers. Or call EditValue("Mattew", 6, true);
to edit only first number in line and EditValues("Mattew", 4, false);
to edit second number in line.
If you can't be sure that each line matches "String Number1 Number2" scheme, you can add some check before parsing to int
(such as !string.IsNullOrEmpty(lineValues[1])
) or use int.TryParse(lineValues[1], out int currentValue1)
.
CodePudding user response:
You can use this function for find and replace row in file
public static bool lineChanger(string fileName, string name, int first_num, int sec_num)
{
//check for exist file
if (!File.Exists(fileName))
return false;
var lines = File.ReadAllLines(fileName).ToList();
string item = lines.FirstOrDefault(x => x.Substring(0, x.IndexOf(" ")).ToLower() == name.ToLower());
if (item == null)
return false;
//remove an insert new line
lines.Remove(item);
var record = item.Split(" ");
item = $"{record[0]} {Convert.ToInt32(record[1]) first_num} {Convert.ToInt32(record[2]) sec_num}";
lines.Add(item);
File.WriteAllLines(fileName, lines);
return true;
}