Reading and parsing from a text file
Based on What's the fastest way to read a text file line-by-line? using a StreamReader to read line by line to minimize memory usage.
private void LoadSaveData()
{
string fileName = @"c:\test.txt";
const int BufferSize = 128;
using (var fileStream = File.OpenRead(fileName))
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8, true, BufferSize))
{
string line;
while ((line = streamReader.ReadLine()) != null)
{
// Process line
string[] numberStrings = line.Split( );
if(numberStrings.Length == 3
&& float.TryParse(numberStrings[0], out float f1)
&& float.TryParse(numberStrings[1], out float f2)
&& float.TryParse(numberStrings[2].TrimEnd(';'), out float f3))
{
// do something with your floats
}
}
}
}
Reading a text file with c#
Hi Gailen use the following method:
File.ReadAllLines(@"location");
- If location is correct then this will work
- Assign to variable, for example
Recommended ways to read certain things in a text file
If your input file structure is static that means it wont change the order; you can use the below instead of your //ReadLines code.
var allLines = File.ReadAllLines(path);
var dataSet = allLines.Select(line => line.Trim().Split(' ')[1]).ToArray();
// Add conditional checks regarding the length of the dataset and any thing else.
var userName = dataSet[0];
var accesscode = Convert.ToInt32(dataSet[1]);
var value = Convert.ToInt32(dataSet[2]);
var email = dataSet[3];
// Then your console.writeline statements here.
If you are unsure of the order, you can use dictionary to store the both parts of line split one for key and other for value. And then print them.
C# reading a string from text file, splitting and putting into tabstring
Your problem is here:
while (srListOfObjects.ReadLine() != null)
{
string myString= (srListOfObjects.ReadLine();
You are entering the loop on the condition that srListOfObjects.ReadLine()
returns something other than null
but then you are immediately reading a new line form srListOfObjects
and storing the returned reference in myString
. This has obviously two problems:
- The second call to
ReadLine
can returnnull
and you are not checking if it is. The error you are getting is due to this reason. - You are losing information. You are ignoring the line you are reading when checking the while condition. Until your program crashes or runs to the end (depends on wether the input file has even or odd number of lines), you will process only half of the data.
Update:
You should only read one line per iteration. One way to do it is declaring and initializing myString
before entering the loop and updating it on every iteration:
var myString = srListOfObjects.ReadLine();
while (myString != null)
{
//do your stuff
myString = srListOfObjects.ReadLine();
}
Read numbers from a text file in C#
Brannon's answer explains how to read binary data. If you want to read text data, you should be reading strings and then parsing them - for which there are built-in methods, of course.
For example, to read a file with data:
10
10.5
hello
You might use:
using (TextReader reader = File.OpenText("test.txt"))
{
int x = int.Parse(reader.ReadLine());
double y = double.Parse(reader.ReadLine());
string z = reader.ReadLine();
}
Note that this has no error handling. In particular, it will throw an exception if the file doesn't exist, the first two lines have inappropriate data, or there are less than two lines. It will leave a value of null
in z
if the file only has two lines.
For a more robust solution which can fail more gracefully, you would want to check whether reader.ReadLine()
returned null
(indicating the end of the file) and use int.TryParse
and double.TryParse
instead of the Parse
methods.
That's assuming there's a line separator between values. If you actually want to read a string like this:
10 10.5 hello
then the code would be very similar:
using (TextReader reader = File.OpenText("test.txt"))
{
string text = reader.ReadLine();
string[] bits = text.Split(' ');
int x = int.Parse(bits[0]);
double y = double.Parse(bits[1]);
string z = bits[2];
}
Again, you'd want to perform appropriate error detection and handling. Note that if the file really just consisted of a single line, you may want to use File.ReadAllText
instead, to make it slightly simpler. There's also File.ReadAllLines
which reads the whole file into a string array of lines.
EDIT: If you need to split by any whitespace, then you'd probably be best off reading the whole file with File.ReadAllText
and then using a regular expression to split it. At that point I do wonder how you represent a string containing a space.
In my experience you generally know more about the format than this - whether there will be a line separator, or multiple values in the same line separated by spaces, etc.
I'd also add that mixed binary/text formats are generally unpleasant to deal with. Simple and efficient text handling tends to read into a buffer, which becomes problematic if there's binary data as well. If you need a text section in a binary file, it's generally best to include a length prefix so that just that piece of data can be decoded.
c# read a text file. How to avoid reading it again
Like I said in my comment, just read the entire file once and save it into a List<string>
using File.ReadAllLines() (Cast the output to a list). Once you have that, then you can just use the List<string>
directly without having to go back to read the file each time. See below.
public class Program
{
private static List<string> lines;
public static void Main()
{
// At this point lines will have the entire file. Each line in a different index in the list
lines = File.ReadAllLines("..path to file").ToList();
useList(); // Use it however
}
// Just use the List which has the same data as the file
public static string readFromList(int num)
{
return lines[num];
}
public static void useList()
{
string line1 = readFromList(1); // Could even be string line1 = lines[SomeNum];
string line2 = readFromList(2);
}
}
Can not read from the text file specified in c#.net
The problem here is that your docPath variable doesn't hold the path to a single file, but instead the path of a folder. (C:\{User}\Documents)
So the File.Exists check will always fail, because you're targeting the folder.
Try combining your docPath with the actual file name and it should work.
Related Topics
How to Confirm That Mail Has Been Delivered or Not
How to Delay Shutdown and Run a Process in Window Service
How to Get the Access Token from a Blazor (Server-Side) Web App
Exception Using Copytodatatable with "New {..}" Linq Query
Send Email via C# Through Google Apps Account
How to Write Logs from Within Startup.Cs
Read Binary File into a Struct
Iterating Over JSON Object in C#
Float/Double Precision in Debug/Release Modes
Convert Am/Pm Time to 24 Hours Format
Pass a Value from One Form to Another
JSON.Net Serialize Directly from Oledbconnection
Crud Operations Using Datagridview, Datatable and Dataadapter - Cannot Add New Row to Datagridview
C# Passing Function as Argument