I've been having some problems extracting particular lines in a txt file.
I'm using the file to store user names for a login program.
The program will know what line to go to in the text file but I don't know how to actually get the wanted line out and put the resulting string into a variable.
Code I'm using to pull file into a variable is:
string usernameFile = System.IO.File.ReadAllText(#"Usernames.txt");
My real problem is that code two lines below doesn't work in my visual studios community version 2017:
File.ReadLine
I don't know if I need to install something else onto my visual studios but any method to be able to read a particular line of a txt file will be fine.
Use File.ReadAllLines instead. That gives you an array of strings, one for each line.
string[] lines = File.ReadAllLines("Usernames.txt");
string username = lines[2]; // or whatever.
You can use LINQ to avoid reading the entire file:
var line = File.ReadLines("Usernames.txt").Skip(2).First();
Related
I'm currently writing an application in .NET which reads from a file - in that file, there is a path to another file written. The application then prints the content of that file.
This is an example:
File 1:
D:\Path\To\My\File.txt
SOME OTHER STUFF
File 2:
Hello, world!
When I run my application, it throws an error saying the syntax of the path is invalid. I tried seeing the actual string it takes from File 1, so I did this:
string testString = File.ReadAllText(file); // file is a variable that's already created, which is just a string with the path of File 1.
File.WriteAllText("test.txt", $"'{testString}'");
I looked into the newly created test.txt and saw this.
'D:\Path\To\My\File.txt
'
Why is there a line break before the second quote? I tried googling this with no success. Please help me with this, I am new to C#.
Edit 1:
I tried using File.ReadAllBytes(), but the results were the same.
This is the outcome:
'D:\Georges\Desktop\G\test2.g
'
And this is my code:
byte[] testString = File.ReadAllBytes(file);
File.WriteAllBytes("test.txt", testString);
Edit 2:
When I deleted everything from the file EXCEPT that one line, it worked. That's good, but I do want to be able to add more lines to my file without it not working.
maybe you should use File.ReadLines instead of File.ReadAllText. something like this:
string testString = File.ReadLines(file).ToList()[0]; // file is a variable that's already created, which is just a string with the path of File 1.
File.WriteAllText("test.txt", $"'{testString}'");
You don't show your code, so I cannot be sure this is your problem, but from experience, it looks like it is..
Your filename probably has an unseen character inside at the end of it, so when you copy-paste the filename into the text-file you also copied it with that special character.
As some special characters are unseen the counter-intuitive thing that happens here is that you don't expect your file-name that looks to you like 'test2.g' to actually contain 'test2.g'+chr(13) - where char-13 is i.e. a linefeed character.
It's a bit hard to explain but I'll try my best.
I'm not asking how to create a text file or read text file and display. It's more basic than that.
My question is: I've written a paragraph of text file but I don't know how to put it under Solution Explorer, so my program can reference it instead of writing it many times.
Here is one of my coding with a sample string and I have a couple of them using the same text but different tasks. Here I manually(?) wrote the text(string) that I want to save as text file so I can refer to.
string st = "I like apples. I like red apples. I like red apples than green apples";
string result = st.OrderByDescending(s => s.Split(' ').Count()).First();
this.lblMostWordsInSen.Text = result;
Actually, the code above has an error under Split, it says char doesn't contain a definition for Split. How do I fix it?
I've found this coding below "text_file_name.txt" or (#"d:\test.txt") is what I want but file should not be stored in my D drive. It should be stored in my program (Solution Explorer?) I did it in Web application but I don't know how to do in WinForm.
string filename = "Alice-in-Wonderland.txt";
StreamReader sr = new StreamReader("TestFile.txt")
String[] values = File.ReadAllText(#"d:\test.csv").Split(',');
And finally how to call my file is my last question...
Thanks in advance~
Actually, the code above has an error under Split, it says char
doesn't contain a definition for Split. How do I fix it?
string result = st.OrderByDescending(s => s.Split(' ').Count()).First();
it is because string st is a group of characters. in fact it is
st[0],st[1],...,st[st.Length-1]
when you call st.OrderByDescending and supply a lambda expression like s => ..., s does not represent the whole string(st), it just represents elements of st which their type is char and this results to the error we have mentioned above.
You can add a text file to your projects. and if you want to read them you can just read them like this
File.ReadAllText("yourfilename")
but remember to select your file in solution explorer and right click and click properties, then change "Copy to output directory" property to the "Copy always" or "Copy if newer" based on your situation, this will cause that when you build your project, this file will be copied in the directory where your executable file is and you do not need path of it to access it.
you can also go to Build Events tab of your project properties and set actions that will execute when you try to build your project, for example you can set an action to copy "yourfile" to a folder named "text resources" in your build directory, in this approach you can handle more complex situation for example when you have lot of this kind of resources in your project.
you can read this for more information on Build Events
Instead of using the Resources of your program as suggested in the comments already, you could also use a Settings file if you want these Settings to be easily manipulated.
Check this article out: http://msdn.microsoft.com/en-us/library/aa730869(v=vs.80).aspx
So I am trying to save file paths in text documents so that I can later edit them easily without changing any of the code.
How would I go about doing this? I was thinking using an array with a statement like this:
foreach (string ExamplePath: in line)
Then when the program detects that line, it skips a space then reads the rest of the line and then makes that a string. I just don't know how to do this.
I currently have two strings assigned - domain,subdomain
How could I delete any matched occurrences of these strings in a text file?
string domain = "127.0.0.1 test.com"
string subdomain = "127.0.0.1 sub.test.com"
I don't think using a regex would be ideal in this situation.
How can this be done?
You need to:
Open the existing file for input
Open a new file for output
Repeatedly:
Read a line of text from the input
See if it matches your pattern (it's unclear at the moment what pattern you're looking for)
If it doesn't, write the line to the output (or if you're only trying to remove bits of lines, work out which bit you want to write out)
Close both the input and output (a using statement will do this automatically)
Optionally delete the original file and rename the new one if you want to effectively replace the original.
var result = Regex.Replace(File.ReadAllText("file.txt"),
#"127\.0\.0\.1 test\.com|127\.0\.0\.1 sub\.test\.com", string.Empty);
Then write to file obtained result.
Hello I am working on something, and I need to be able to be able to add text into a .txt file. Although I have this completed I have a small problem. I need to write the string in the middle of the file more or less. Example:
Hello my name is Brandon,
I hope someone can help, //I want the string under this line.
Thank you.
Hopefully someone can help with a solution.
Edit Alright thanks guys, I'll try to figure it out, probably going to just rewrite the whole file. Ok well the program I am making is related to the hosts file, and not everyone has the same hosts file, so I was wondering if there is a way to read their hosts file, and copy all of it, while adding the string to it?
With regular files there's no way around it - you must read the text that follows the line you wish to append after, overwrite the file, and then append the original trailing text.
Think of files on disk as arrays - if you want to insert some items into the middle of an array, you need to shift all of the following items down to make room. The difference is that .NET offers convenience methods for arrays and Lists that make this easy to do. The file I/O APIs offer no such convenience methods, as far as I'm aware.
When you know in advance you need to insert in the middle of a file, it is often easier to simply write a new file with the altered content, and then perform a rename. If the file is small enough to read into memory, you can do this quite easily with some LINQ:
var allLines = File.ReadAllLines( filename ).ToList();
allLines.Insert( insertPos, "This is a new line..." );
File.WriteAllLines( filename, allLines.ToArray() );
This is the best method to insert a text in middle of the textfile.
string[] full_file = File.ReadAllLines("test.txt");
List<string> l = new List<string>();
l.AddRange(full_file);
l.Insert(20, "Inserted String");
File.WriteAllLines("test.txt", l.ToArray());
one of the trick is file transaction. first you read the file up to the line you want to add text but while reading keep saving the read lines in a separate file for example tmp.txt and then add your desired text to the tmp.txt (at the end of the file) after that continue the reading from the source file till the end. then replace the tmp.txt with the source file. at the end you got file with added text in the middle :)
Check out File.ReadAllLines(). Probably the easiest way.
string[] full_file = File.ReadAllLines("test.txt");
List<string> l = new List<string>();
l.AddRange(full_file);
l.Insert(20, "Inserted String");
File.WriteAllLines("test.txt", l.ToArray());
If you know the line index use readLine until you reach that line and write under it.
If you know exactly he text of that line do the same but compare the text returned from readLine with the text that you are searching for and then write under that line.
Or you can search for the index of a specified string and writ after it using th escape sequence \n.
As others mentioned, there is no way around rewriting the file after the point of the newly inserted text if you must stick with a simple text file. Depending on your requirements, though, it might be possible to speed up the finding of location to start writing. If you knew that you needed to add data after line N, then you could maintain a separate "index" of the offsets of line numbers. That would allow you to seek directly to the necessary location to start reading/writing.