Replace a word from a specific line in a text file - c#

I'm working on a little test program to experiment with text files and storing some data in them, and I've stumbled accross a problem when trying to replace a value in a specific line.
This is how the formatting of my text file is done :
user1, 1500, 1
user2, 1700, 17
.. and so on.
This is the code I am using at the moment to read the file line by line :
string line;
Streamreader sr = new Streamreader(path);
while ((line = sr.ReadLine()) != null)
{
string[] infos = line.Split(',');
if (infos[0] == username) //the username is received as a parameter (not shown)
//This is where I'd like to change the value
}
Basically, my objective is to update the number of points (the second value in the text line - infos[1]) only if the username matches. I tried using the following code (edited to match my informations)
string text = File.ReadAllText("test.txt");
text = text.Replace("some text", "new value");
File.WriteAllText("test.txt", text);</pre>
The problem with this is that it will replace every corresponding value in the text file, and not just the one of the correct line (specified by the matching username). I know how to change the value of infos[1] (ex: 1500 for user1) but I don't know how to rewrite it to the file after that.
I've searched online and on StackOverflow, but I couldn't find anything for this specific problem where the value is only to be modified if it's on the proper line - not anywhere in the text.
I run out of ideas on how to do this, I would really appreciate some suggestions.
Thank you very much for your help.

Try this:
var path = #"c:\temp\test.txt";
var originalLines = File.ReadAllLines(path);
var updatedLines = new List<string>();
foreach (var line in originalLines)
{
string[] infos = line.Split(',');
if (infos[0] == "user2")
{
// update value
infos[1] = (int.Parse(infos[1]) + 1).ToString();
}
updatedLines.Add(string.Join(",", infos));
}
File.WriteAllLines(path, updatedLines);

use ReadLines and LINQ:
var line = File.ReadLines("path")
.FirstOrDefault(x => x.StartsWith(username));
if (line != null)
{
var parts = line.Split(',');
parts[1] = "1500"; // new number
line = string.Join(",", parts);
File.WriteAllLines("path", File.ReadLines("path")
.Where(x => !x.StartsWith(username)).Concat(new[] {line});
}

Related

how can i search a file find a string and get all the text between / /

ok i trying my best to get this string
"/i/models/fc6d6067621442ebb6f4238636363d47/textures?optimized=1"
but i need to get the jumble of numbers and between the // only and save it to a string because each json file i open has a different amount of numbers
i tried using regex but it finds different concordances in the file and i only need the one that matches this line
the file is a json file
https://i.imgur.com/B98gdBD.png
but not sure how to accomplish this
this is the code i tried
List<string> found = new List<string>();
string line;
using (StreamReader file = new StreamReader(Application.StartupPath + "\\textures.json"))
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains("textures?optimized=1"))
{
texturemodel = line;
}
}
}
this code does work and does get the line needed only issue i have with it it has ;} on the end of it so its nearly working but not sure how to remove the white space at the start and the ;{ at the end of the file the white space is at the beginning of the file
thanks in advance elfenliedtopfan5
if you are sure that that would always be the format, try string.Split()
var stringWithJumbledNumbersAndLetters = "/i/models/fc6d6067621442ebb6f4238636363d47/textures?optimized=1";
var splitString = stringWithJumbledNumbersAndLetters.Split('/');
//splitString[0] = i;
//splitString[1] = models;
//splitString[2] = fc6d6067621442ebb6f4238636363d47;
//splitString[3] = textures?optimized=1;
return splitString[2];
or direct would be
var stringWithJumbledNumbersAndLetters = "/i/models/fc6d6067621442ebb6f4238636363d47/textures?optimized=1";
return stringWithJumbledNumbersAndLetters.Split('/')[2];
String s = "/i/models/fc6d6067621442ebb6f4238636363d47/textures?optimized=1";
String[] result = s.split("/");
System.out.println(result[3]);

Fill Textboxes With Information From .txt File

I have this text in a .txt file
Username:Password
Username2:Password2
Username3:Password3
And i want to set the value of line 2(example) inside the .txt file to the textboxes
This is what i mean:
Textbox1.text = Username2;
Textbox2.text = Password2;
Any links that could provide help are really appreciated, thanks in advance
You can do like this :
// Reading all lines of files
var txtLines = File.ReadAllLines("your_file_path");
// Make sure, there should be atleast more than one line
// as you want to get username/password from second line
if(txtLines != null && txtLines.Count() > 1)
{
// Skip first line and after that get first line
var secondLine = txtLines.ToList().Skip(1).First();
// split it by colon
var splittedText = secondLine.Split(':');
if(splittedText.Count() > 1)
{
Textbox1.Text = splittedText[0];
Textbox2.Text = splittedText[1];
}
}

Deleting text from text file

I want to know how I can delete a certain amount of text from a file on each line.
I can not think of a way of accomplishing such a task.
878 57 2
882 63 1
887 62 1
1001 71 0
1041 79 1
1046 73 2
This is what the text file looks like but I only want the numbers that are on the very left. I can not manually the 2 rows on the right because there is over 16,000 lines of this.
The numbers on the left also change in length so I can't read them by length.
I'm also not sure what character the numbers are separated by, it may be tab.
Anyone have any ideas on what I could try?
If you wish to take a look at the text file, here: http://pastebin.com/xyaCsc6W
var query = File.ReadLines("input.txt")
.Where(x => char.IsDigit(x.FirstOrDefault()))
.Select(x => string.Join("", x.TakeWhile(char.IsDigit)));
File.WriteAllLines("output.txt", query);
string line;
using (var sr = new StreamReader(#"E:\test1.txt"))
{
using (var sw = new StreamWriter(#"E:\test1.tmp"))
{
while (!sr.EndOfStream)
{
line = sr.ReadLine();
line = Regex.Match(line, #"([\d]*)").Groups[1].Value;
sw.WriteLine(line);
}
}
}
File.Replace(#"E:\test1.tmp", #"E:\test1.txt", null);
You could do:
var col =
from s in File.ReadAllLines(input_file_name);
select s.Split(" ".ToCharArray())[0];
Note: In the Split(" ") I have a space and a tab characters.
StringBuilder sb = new StringBuilder();
//read the line by line of file.txt
using (StreamReader sr = new StreamReader("file.txt"))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
//for each line identify the space
//cut the data from beginning of each line to where it finds space
string str = line.Substring(0, line.IndexOf(' '));
//Append each modifed line into string builder object
sb.AppendLine(str);
}
}
//Create temp newfile
using (File.Create("newfile.txt"))
{
//create newfile to store the modified data
}
//Add modified data into newfile
File.WriteAllText("newfile.txt",sb.ToString());
//Replace with new file
File.Replace("newfile.txt", "file.txt", null);
You could also do this which will give you a list of results of only the left (column) characters (numeric/alphanumeric) of the text file:
var results = File.ReadAllLines("filename.txt")
.Select(line => line.Split('\t').First())
.ToList();
It looks like the text file is delimited by tabs.
To save the list of results back into a text file add the following in addition:
File.WriteAllLines("results.txt", results.ToArray());

C# get text from file between two hashes

In my C# program (at this point) I have two fields in my form. One is a word list using a listbox; the other is a textbox. I have been able to successfully load a large word list into the listbox from a text file. I can also display the selected item in the listbox into the textbox this way:
private void wordList_SelectedIndexChanged(object sender, EventArgs e)
{
string word = wordList.Text;
concordanceDisplay.Text = word;
}
I have another local file I need to get at to display some of its contents in the textbox. In this file each headword (as in a dictionary) is preceded by a #. So, I would like to take the variable 'word' and search in this local file to put the entries into the textbox, like so:
#headword1
entry is here...
...
...
#headword2
entry is here...
...
...
#headword3
entry is here...
...
...
You get the format of the text file. I just need to search for the correct headword with # before that word, and copy all info from there until the next hash in the file, and place it in the text box.
Obviously, I am a newbie, so be gentle. Thanks much.
P.S. I used StreamReader to get at the word list and display it in the listbox like so:
StreamReader sr = new StreamReader("C:\\...\\list-final.txt");
string line;
while ((line = sr.ReadLine()) != null)
{
MyList.Add(line);
}
wordList.DataSource = MyList;
var sectionLines = File.ReadAllLines(fileName) // shortcut to read all lines from file
.SkipWhile(l => l != "#headword2") // skip everything before the heading you want
.Skip(1) // skip the heading itself
.TakeWhile(l => !l.StartsWith("#")) // grab stuff until the next heading or the end
.ToList(); // optional convert to list
string getSection(string sectionName)
{
StreamReader sr = new StreamReader(#"C:\Path\To\file.txt");
string line;
var MyList = new List<string>();
bool inCorrectSection = false;
while ((line = sr.ReadLine()) != null)
{
if (line.StartsWith("#"))
{
if (inCorrectSection)
break;
else
inCorrectSection = Regex.IsMatch(line, #"^#" + sectionName + #"($| -)");
}
else if (inCorrectSection)
MyList.Add(line);
}
return string.Join(Environment.NewLine, MyList);
}
// in another method
textBox.Text = getSection("headword1");
Here are a few alternate ways to check if the section matches, in rough order of how accurate they are in detecting the right section name:
// if the separator after the section name is always " -", this is the best way I've thought of, since it will work regardless of what's in the sectionName
inCorrectSection = Regex.IsMatch(line, #"^#" + sectionName + #"($| -)");
// as long as the section name can't contain # or spaces, this will work
inCorrectSection = line.Split('#', ' ')[1] == sectionName;
// as long as only alphanumeric characters can ever make up the section name, this is good
inCorrectSection = Regex.IsMatch(line, #"^#" + sectionName + #"\b");
// the problem with this is that if you are searching for "head", it will find "headOther" and think it's a match
inCorrectSection = line.StartsWith("#" + sectionName);

split a string from a text file into another list

Hi i know the Title might sound a little confusing but im reading in a text file with many lines of data
Example
12345 Test
34567 Test2
i read in the text 1 line at a time and add to a list
using (StreamReader reader = new StreamReader("Test.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
list.Add(line);
}
}
how do i then separate the 1234 from the test so i can pull only the first column of data if i need like list(1).pars[1] would be 12345 and list(2).pars[2] would be test2
i know this sounds foggy but i hope someone out there understands
Maybe something like this:
string test="12345 Test";
var ls= test.Split(' ');
This will get you a array of string. You can get them with ls[0] and ls[1].
If you just what the 12345 then ls[0] is the one to choose.
If you're ok with having a list of string[]'s you can simply do this:
var list = new List<string[]>();
using (StreamReader reader = new StreamReader("Test.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
list.Add(line.Split(' '));
}
}
string firstWord = list[0][0]; //12345
string secondWord = list[0][1]; //Test
When you have a string of text you can use the Split() method to split it in many parts. If you're sure every word (separated by one or more spaces) is a column you can simply write:
string[] columns = line.Split(' ');
There are several overloads of that function, you can specify if blank fields are skipped (you may have, for example columns[1] empty in a line composed by 2 words but separated by two spaces). If you're sure about the number of columns you can fix that limit too (so if any text after the last column will be treated as a single field).
In your case (add to the list only the first column) you may write:
if (String.IsNullOrWhiteSpace(line))
continue;
string[] columns = line.TrimLeft().Split(new char[] { ' ' }, 2);
list.Add(columns[0]);
First check is to skip empty or lines composed just of spaces. The TrimLeft() is to remove spaces from beginning of the line (if any). The first column can't be empty (because the TrimLeft() so yo do not even need to use StringSplitOptions.RemoveEmptyEntries with an additional if (columns.Length > 1). Finally, if the file is small enough you can read it in memory with a single call to File.ReadAllLines() and simplify everything with a little of LINQ:
list.Add(
File.ReadAllLines("test.txt")
.Where(x => !String.IsNullOrWhiteSpace(x))
.Select(x => x.TrimLeft().Split(new char[] { ' ' }, 2)[0]));
Note that with the first parameter you can specify more than one valid separator.
When you have multiple spaces
Regex r = new Regex(" +");
string [] splitString = r.Split(stringWithMultipleSpaces);
var splitted = System.IO.File.ReadAllLines("Test.txt")
.Select(line => line.Split(' ')).ToArray();
var list1 = splitted.Select(split_line => split_line[0]).ToArray();
var list2 = splitted.Select(split_line => split_line[1]).ToArray();

Categories