Fill Textboxes With Information From .txt File - c#

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];
}
}

Related

Replace a word from a specific line in a text file

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});
}

Streamreader isn't returning the correct values from my text file, can't figure out how to properly read my text files C#

I'm running three counters, one to return the total amount of chars, one to return the number of '|' chars in my .txt file (total). And one to read how many separate lines are in my text file. I'm assuming my counters are wrong, I'm not sure. In my text file there are some extra '|' chars, but that is a bug I need to fix later...
The Message Boxes show
"Lines = 8"
"Entries = 8"
"Total Chars = 0"
Not sure if it helps but the .txt file is compiled using a streamwriter, and I have a datagridview saved to a string to create the output. Everything seems okay with those functions.
Here is a copy of the text file I'm reading
Matthew|Walker|MXW320|114282353|True|True|True
Audrey|Walker|AXW420|114282354|True|True|True
John|Doe|JXD020|111222333|True|True|False
||||||
And here is the code.
private void btnLoadList_Click(object sender, EventArgs e)
{
var loadDialog = new OpenFileDialog
{
InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments),
Filter = "Text (*.txt)|*.txt",
FilterIndex = 1
};
if (loadDialog.ShowDialog() != DialogResult.OK) return;
using (new StreamReader(loadDialog.FileName))
{
var lines = File.ReadAllLines(loadDialog.FileName);//Array of all the lines in the text file
foreach (var assocStringer in lines)//For each assocStringer in lines (Runs 1 cycle for each line in the text file loaded)
{
var entries = assocStringer.Split('|'); // split the line into pieces (e.g. an array of "Matthew", "Walker", etc.)
var obj = (Associate) _bindingSource.AddNew();
if (obj == null) continue;
obj.FirstName = entries[0];
obj.LastName = entries[1];
obj.AssocId = entries[2];
obj.AssocRfid = entries[3];
obj.CanDoDiverts = entries[4];
obj.CanDoMhe = entries[5];
obj.CanDoLoading = entries[6];
}
}
}
Hope you guys find the bug(s) here. Sorry if the formatting is sloppy I'm self-taught, no classes. Any extra advice is welcomed, be as honest and harsh as need be, no feelings will be hurt.
In summary
Why is this program not reading the correct values from the text file I'm using?
Not totally sure I get exactly what you're trying to do, so correct me if I'm off, but if you're just trying to get the line count, pipe (|) count and character count for the file the following should get you that.
var lines = File.ReadAllLines(load_dialog.FileName);
int lineCount = lines.Count();
int totalChars = 0;
int totalPipes = 0; // number of "|" chars
foreach (var s in lines)
{
var entries = s.Split('|'); // split the line into pieces (e.g. an array of "Matthew", "Walker", etc.)
totalChars += s.Length; // add the number of chars on this line to the total
totalPipes = totalPipes + entries.Count() - 1; // there is always one more entry than pipes
}
All the Split() is doing is breaking the full line into an array of the individual fields in the string. Since you only seem to care about the number of pipes and not the fields, I'm not doing much with it other than determining the number of pipes by taking the number of fields and subtracting one (since you don't have a trailing pipe on each line).

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);

Parse text from a .txt file uploaded to memory in desired format C#

fairly new to C# here......What I'm trying to do is parse a bunch of text to a webpage from a .txt file uploaded to memory.
Here's what the .txt file looks like
.RES B7=121
.RES C12=554
.RES VMAX=4.7μV
Again, it goes on like this for another 50 or so .RES'...
I've successfully got it to parse, but not in the desired format...
Here's how I want it to look on the webpage
B7.........121
C12.........554
VMAX.........4.7μV
all inside of a hidden panel with id="outpt"... which is currently set to visible="false"
Here's the code i'm using in my C# Page
namespace Sdefault
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUpld_Click(object sender, EventArgs e)
{
Stream theStream = file1.PostedFile.InputStream; //uploads .txt file to memory for parse
using (StreamReader sr = new StreamReader(theStream))
{
string tba;
while ((tba = sr.ReadLine()) != null)
{
string[] tmpArray = tba.Split(Convert.ToChar("=")); //Splits ".RES B7=121" to "B7"... but for some reason, It prints it as
//".RES B7.RES C12.RES VMAX"... I would ultimately desire it to be printed as shown above
Response.Write(tmpArray[0].ToString());
var.Text = tba;
outpt.Visible = true;
}
}
}
}
}
Any pointers in which direction I should go with this?
// Open the file for reading
using (StreamReader reader = new StreamReader((Stream)file1.PostedFile.InputStream))
{
// as long as we have content to read, continue reading
while (reader.Peek() > 0)
{
// split the line by the equal sign. so, e.g. if:
// ReadLine() = .RES B7=121
// then
// parts[0] = ".RES b7";
// parts[1] = "121";
String[] parts = reader.ReadLine().split(new[]{ '=' });
// Make the values a bit more bullet-proof (in cases where the line may
// have not split correctly, or we won't have any content, we default
// to a String.Empty)
// We also Substring the left hand value to "skip past" the ".RES" portion.
// Normally I would hard-code the 5 value, but I used ".RES ".Length to
// outline what we're actually cutting out.
String leftHand = parts.Length > 0 ? parts[0].Substring(".RES ".Length) : String.Empty;
String rightHand = parts.Length > 1 ? parts[1] : String.Empty;
// output will now contain the line you're looking for. Use it as you wish
String output = String.Format("<label>{0}</label><input type=\"text\" value=\"{1}\" />", leftHand, rightHand);
}
// Don't forget to close the stream when you're done.
reader.Close();
}
Not sure on your formatting, but a simple Split and Format will do the trick.
On your split, you're getting everything before the = sign, whereas from your description, you want everything after it. e.g.
while(...)
{
var line = String.Format("<label>{0}< />.........textbox>{0}< />",tba.Split('=')[1]);
Response.Write(line);
}
if you take .RES B7=121 and split it on "=" then the index 0 would be .RES B7 and index one would be 121
if you want to further subdivide you wil have to split index 0 again using Chr(32) which would yield .RES as 0 and B7 as 1.
Can be done inline as suggested above with string formatting.
It looks as though you want someling like
String.Format("<label>{0}< />.........textbox>{1}< />",tba.Split('=')[0].Split(' ')[1],tba.Split('=')[1].);
Ok.. you have several issues here..
first, you are spliting using the =.. so you are splitting the string in two parts...
.RES B7=121 comes to:
tmpArray[0] = .RES B7
tmpArray[1] = 121
To avoid another split, the best you can do is to replace .RES with and empty string:
tmpArray[0] = tmpArray[0].replace(".RES","");
Then, you should be showing this somewhere on your page, so you should be writting:
Response.Write("<label>" + tmpArray[0].ToString() + "< />" + "<textbox>" + tmpArray[1].ToString() + "< />");
Looks like you need to do 2 splits:
1st var tmpArr1 = tba.Split(' ') will result in a string array {".RES","B7=121"}
2nd var tmpArr2 = tmpArr1[1].split('=') will result in a string array {"B7","121"}
Then you can do:
var line = String.Format("<label>{0}</label><textbox>{1}</textbox>",tmpArr2[0],tmpArr2[1]);
Response.Write(line);

txt file read/overwrite/append. Is this feasible? (Visual C#)

I'm writing a program for some data entry I have to periodically do. I have begun testing a few things that the program will have to do but i'm not sure about this part.
What i need this part to do is:
read a .txt file of data
take the first 12 characters from each line
take the first 12 characters from each line of the data that has been entered in a multi-line text box
compare the two lists line by line
if one of the 12 character blocks from the multi-line text box match one of the blocks in the .txt file then overwrite that entire line (only 17 characters in total)
if one of the 12 character blocks from the multi-line text box DO NOT match any of the blocks in the.txt file then append that entire line to the file
thats all it has to do.
i'll do an example:
TXT FILE:
G01:78:08:32 JG05
G08:80:93:10 JG02
G28:58:29:28 JG04
MULTI-LINE TEXT BOX:
G01:78:08:32 JG06
G28:58:29:28 JG03
G32:10:18:14 JG01
G32:18:50:78 JG07
RESULTING TXT FILE:
G01:78:08:32 JG06
G08:80:93:10 JG02
G28:58:29:28 JG03
G32:10:18:14 JG01
G32:18:50:78 JG07
as you can see lines 1 and 3 were overwriten, line 2 was left alone as it did not match any blocks in the text box, lines 4 and 5 were appended to the file.
thats all i want it to do.
How do i go about this?
Thanks in advance
Edit
The code i'm using is this:
private void WriteToFile()
{
// Read all lines from file into memory
System.IO.StreamReader objReader = new System.IO.StreamReader("Jumpgate List.JG");
List<String> fileTextList = new List<String>();
do
{
fileTextList.Add(objReader.ReadLine());
}
while (objReader.Peek() != -1);
objReader.Close();
// Read all lines from the Input textbox into memory
System.IO.StringReader objReaderi = new System.IO.StringReader(txtInput.Text);
List<String> inputTextList = new List<String>();
do
{
inputTextList.Add(objReaderi.ReadLine());
}
while (objReaderi.Peek() != -1);
objReaderi.Close();
for(int i=0;i<fileTextList.Count;i++)
{
for(int j=0;j<inputTextList.Count;j++)
//compare the first 12 characters of each string
if (String.Compare(fileTextList[i], 0, inputTextList[j], 0, 12) == 0) // strings are equal
{
//replace the fileTextList string with the inputTextList string
fileTextList[i] = inputTextList[j];
// now that you have matched you inputTextList line you remember not to append it at the end
inputTextList[j] = String.Empty; // or nothing
}
}
for(int i=0;i<inputTextList.Count;i++)
{
if (!string.IsNullOrEmpty(inputTextList[i])) fileTextList.Add(inputTextList[i]);
}
System.IO.StreamWriter objWriter = new System.IO.StreamWriter("Jumpgate List.JG");
// Overwrite the Jumpgate List.JG file using the updated fileTextList
objWriter.Write(fileTextList);
objWriter.Close();
}
However, when i open the txt file all i get is: System.Collections.Generic.List`1[System.String]
I'm not going to write the whole code for doing this but it would be something like this:
Disclaimer: I have not used a code editor to try the code, just wrote it here, hopefully you'll get the idea and fill in the missing pieces :)
1) get all the lines in the file in a list. Something like this
StreamReader rd = new StreamReader("sadasd");
List<String> llist = new List<String>();
do
{
llist.Add(rd.ReadLine());
} while (rd.Peek() != -1);
2) get all the lines in your multiline text box (the procedure should be similar to the one above): multiTextList
3) now that you can compare the content of the 2 lists iterating through them
for(int i=0;i<fileTextList.Count;i++)
{
for(int j=0;j<multiTextList.Count;j++)
//compare the first 12 characters of each string
if String.Compare(fileTextList[i], 0, multiTextList[j], 0, 12) == 0 // strings are equal
{
//replace the initial line with whatever you want
fileTextList[i] = //whatever
// now that you have matched you multiTextList line you remember not to append it at the end
multiTextList[j] = String.empty // or nothing
}
}
4) at the end you will have in fileTextList the initial rows, modified where necessary
In multiTextList you will have only the lines that were not matched so we add them to the initial file rows
for(int i=0;i<multiTextList.Count;i++)
{
if !string.isnullorempty(multitextlist[i]) fileTextList.add(multitextlist[i])
}
5) now in fileTextList you have all the rows you require so you can print them one by one in a file and you have your result
StringBuilder lSb = new StringBuilder();
for (int i = 0; i < fileTextList.Count; i++)
{
lSb.AppendLine(fileTextList[i]);
}
File.WriteAllText(#"C:/test2.txt",lSb.ToString());
In C:/test2.txt you should have the results.
Hope this helps!
// this variable maps the timestamps to complete lines
var dict = new Dictionary<string, string>();
// create the map of stamp => line for the original text file
string fileLine = file.ReadLine();
string fileStamp = fileLine.Substring(0, 12);
dict[fileStamp] = fileLine;
// now update the map with results from the text input. This will overwrite text
// strings that already exist in the file
foreach (string inputLine in textInputString.Split('\n'))
{
string inputStamp = inputLine.Substring(0, 12);
dict[inputStamp] = inputLine;
}
// write out the new file with the updated lines
foreach (string line in dict.Values)
{
outputFile.WriteLine(line);
}
if the file is large, loading the entire file into a dictionary to update a handful of lines from a textfield is probably excessive.
In pseudocode I would probably:
Create a list of booleans or other structure to track if a line was matched.
open the file in read/write mode.
For each line in file
{
for each unmatched line in text field
{
If stamps match
Update file
record that it was matched
}
}
for each unmatched line in text field
{
append to file
}
If the lines are fixed width, you can probably optimize by only reading the stamp rather than the whole line. If they match your file pointer is in the right spot to start writing, if not you move to the next line.

Categories