I have seen many examples that show StreamReader taking the arugment "Properties.Resources.someTextFile, and apparently they work great. However, in .net 4.5 I still get:
//while not end of file, read lines of file and split into array
string myFile = Properties.Resources.data;
string line;
StreamReader reader = new StreamReader(myFile);
while ((line = reader.ReadLine()) != null)
{
string[] array = line.Split('#');
string tickerSymbol = array[0];
string regPattern = array[1];
....
So, what am I doing wrong?
By accessing the data text file resource through Properties.Resources the resulting variable myFile should contain the string contents of the file.
string myFile = Properties.Resources.data;
var lines = myFile.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
foreach(var line in lines)
{
// Process each line...
}
Related
I am trying to use this code to create a list. It is failing at the NewCrime Convert step. Not sure how to use the stream reader. It is my first time and I usually use SQL so I have attempted to do the same thing I would do reading SQL here.
List MasterCrimeList;
public List<Crime.Crime> GetList()
{
MasterCrimeList = new List<Crime.Crime>();
try
{
string path = #"F:\\FanshaweCollegeClasses\\Winter2020\\CLAYS_FINAL_EXAM_2020\\VANHEESfinalEXAM\\SacramentocrimeJanuary2006.csv";
if (File.Exists(path))
{
// Open the file to read from.
using (StreamReader sr = File.OpenText(path))
{
string s;
while ((s = sr.ReadLine()) != null)
{
Crime.Crime NewCrime = new Crime.Crime(Convert.ToString(s[0]),//CrimeDateTime
Convert.ToString(s[1]),//CrimeAddress
Convert.ToInt32(Convert.ToString(s[2])),//CrimeDistrict
Convert.ToString(s[3]),//CrimeBeat
Convert.ToInt32(Convert.ToString(s[4])),//CrimeGrid
Convert.ToString(s[5]),//CrimeDescription
Convert.ToInt32(Convert.ToString(s[6])),//ncicCode
decimal.Parse(Convert.ToString(s[7])),//Latitude DECIMAL
decimal.Parse(Convert.ToString(s[8])));//Longitude DECIMAL
MasterCrimeList.Add(NewCrime);
}
}
}
}
When doing s[0] you're reading only one char of the whole line. What you should do is to split each line based on how the values are stored using Split(), and then you can access each value as an array. If it's a csv file:
string s;
while ((s = sr.ReadLine()) != null)
{
string[] lineValues = s.Split(new char[]{','});
string firstValue = lineValues[0];
string secondValue = lineValues[1];
...
}
My code to write text to a file works perfectly...
string path = #"./prefs.dat";
string stringdir = textBox1.Text + Environment.NewLine + textBox2.Text + Environment.NewLine;
System.IO.File.WriteAllText(path, stringdir);
Then to read from the file I use this code which again works perfectly...
Process test = new Process();
string FileName = "prefs.dat";
StreamReader sr = new StreamReader(FileName);
List<string> lines = new List<string>();
lines.Add(sr.ReadLine());
string s = lines[0];
sr.Close();
test.StartInfo.FileName = s;
test.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
test.StartInfo.CreateNoWindow = false;
test.Start();
However when I want to read the 2nd line using the exact same code except changing...
string s = lines[1];
Then it fails, I get a null result. When I look into further the error doesn't even see the 2nd line even though I clearly have two lines.
ReadLine() method reads one line at a time,you need to add all lines by using a while loop following way:
string line="";
while((line = sr.ReadLine()) != null)
{
lines.Add(line);
}
string s = lines[1];
See this MSDN article (Reading a Text File One Line at a Time) for more details
The other way around can be to read all lines at once using ReadAllLines() and then access second line:
string[] lines = System.IO.File.ReadAllLines(stringdir);
string s = lines[1];
See this MSDN article on How to: Read From a Text File
You can also read all lines altogether
string[] lines = System.IO.File.ReadAllLines("path");
If you want to get content of second line as string s = lines[1]; you need to add that to the list first
Process test = new Process();
string FileName = "prefs.dat";
StreamReader sr = new StreamReader(FileName);
List<string> lines = new List<string>();
lines.Add(sr.ReadLine());
lines.Add(sr.ReadLine());
string s1 = lines[0];
string s2 = lines[1]; // Now you can access second line
sr.Close();
test.StartInfo.FileName = s;
test.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
test.StartInfo.CreateNoWindow = false;
test.Start();
When I run my program and there is data in my text file it works as I intended. However, the program crashes if the text file is empty. Therefore, I was wondering how I remedy this issue.
Here is my code for reading from text file:
//This method reads the order data from a text file and assigns the values to each object's variables
void Read_Order_Data()
{
FileStream fs = new FileStream("i:\\OrderData.txt", FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(fs);
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
string[] fields = line.Split('#');
Order[Number_Of_Orders].Order_Number = fields[0];
Order[Number_Of_Orders].Type_Of_Bean = fields[1];
Order[Number_Of_Orders].Quantity_Of_Order = fields[2];
Order[Number_Of_Orders].Date_Of_Purchase = fields[3];
Number_Of_Orders++;
}//end of while statement
reader.Close();
}//end of Read_Order_Data()
If the text file is empty my program stops on this line:
Order[Number_Of_Orders].Type_Of_Bean = fields[1];
When it stops it says Type_Of_Bean is null.
Thanks for any assistance you can offer.
Change your while loop a bit:
string line;
while ((line = reader.ReadLine()) != null)
{
string[] fields = line.Split('#');
...
}
line will be null if the end of the input stream has been reached.
A simpler option may be to use Peek(). I modified the MSDN's example for StreamReader a tiny bit:
string line;
while (reader.Peek() >= 0)
{
line = reader.ReadLine();
...
}
Peek() will return -1 if there are no characters to be read (empty file).
And as others have suggested, make sure your split string array result has the number of fields you plan on indexing. If it doesn't, it might suggest a problem with the file you're reading.
Replace This:
string[] fields = line.Split('#');
With This:
string[] fields = line.Split(new []{'#'},StringSplitOptions.RemoveEmptyEntries);
You should add checking for length of fields in your code, like this:
...
string[] fields = line.Split(new[] {'#'}, StringSplitOptions.RemoveEmptyEntries);
if (fields.Length < 4) break;
...
you can check if field have the correct length
void Read_Order_Data()
{
FileStream fs = new FileStream("i:\\OrderData.txt", FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(fs);
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
string[] fields = line.Split('#');
if (fields.length == 4){
Order[Number_Of_Orders].Order_Number = fields[0];
Order[Number_Of_Orders].Type_Of_Bean = fields[1];
Order[Number_Of_Orders].Quantity_Of_Order = fields[2];
Order[Number_Of_Orders].Date_Of_Purchase = fields[3];
Number_Of_Orders++;
}
}//end of while statement
reader.Close();
}//end of Read_Order_Data()
You can also do
string[] lines = System.IO.File.ReadAllLines("File");
foreach (var line in lines)
{
string[] fields = line.Split('#');
}
If you file is empty, then the following line
string[] fields = line.Split('#');
will give you a string array with only one element (empty string).
Which means that when trying to access the second element (fields[1]), your code will raise an exception.
Short story: you should check the size of the fields array before accessing it.
You can enumerate a line at a time without having to buffer the entire contents like so:
foreach (string line in File.ReadLines("i:\\OrderData.txt"))
{
string[] fields = line.Split('#');
if (fields.Length < 4) // You might also need to add this.
continue;
...
If the file is empty, it will not even enter the body of the loop. It also does not make a copy of the entire file in memory - only one line is buffered in memory at once.
I need to extract some data from a text file and insert to columns in excel sheet. I know how to do this if the rows and the length of the string is known.
try
{
using (System.IO.StreamReader sr = new System.IO.StreamReader("test.txt")
{
string line;
while ((line = sr.ReadLine()) != null)
{
listSNR.Items.Add(line.Substring (78,4));
}
}
}
But the particular text file is complex and the starting index or the length cannot be provided. But the starting word (PCPU01) of the row is known.
Eg: PCPU01,T2716,0.00,0.01,0.00,0.00
output:
T2716 0 0.01 0 0
In that case can somebody please let me know how to extract the texts?
using(System.IO.StreamReader sr = new System.IO.StreamReader("test.txt"))
{
string line;
while((line = sr.ReadLine()) != null)
{
string[] split = line.Split(',');
//...
}
}
split[0] will return "PCPU01", split[1] "T2716" and so on.
You can split one string into an array of strings, separated by a given character. This way, you could split the source string by a comma and use the resulting strings to build your output. Example:
string source = "PCPU01,T2716,0.00,0.01,0.00,0.00";
string[] parts = source.Split(',');
StringBuilder result = new StringBuilder();
result.Append(parts[1]); // The second element in the array, i.e. T2716
result.Append(" ");
result.Append(parts[2]); // 0.00
... // And so on...
return result.ToString() // return a string, not a StringBuilder
I hope this helps a little bit. You might have to tweak it to your needs. But this is a higher level code that gives you general idea of extracting data off a notepad.
DialogResult result = openFileDialog.ShowDialog();
Collection<Info> _infoCollection = new Collection<Info>();
Collection<string> listOfSubDomains = new Collection<string>();
string[] row;
string line;
// READ THE FILE AND STORE IT IN INFO OBJECT AND STORE TAHT INFO OBJECT IN COLLECTION
try
{
using (StreamReader reader = new StreamReader(openFileDialog.FileName))
{
while((line = reader.ReadLine()) != null)
{
Info _info = new Info();
row = line.Split(' ');
_info.FirstName = row[0];
_info.LastName = row[1];
_info.Email = row[2];
_info.Id = Convert.ToInt32(row[3]);
_infoCollection.Add(_info);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
thanks for the answers. What i wanted is to identify the particular line in the text file and split the line into columns. So i was able to do this by calling a GetLine method:
string line15=GetLine(#"test.txt",15);
public string GetLine(string fileName, int line)
{
using (System.IO.StreamReader ssr = new System.IO.StreamReader("test.txt"))
//using (var ssr = new StreamReader("test.txt"))
{
for (int i = 1; i < line; i++)
ssr.ReadLine();
return ssr.ReadLine();
}
}
Then i splitted this line by using the delimiter (,)
This was my approach in C#. It takes a string input (which you can get out of a text file) and an int with which line you want to get. It then separates the string at a given seperator char to a list which in turn is then read out. If the given line number is lower than the count of the created list, the entry is given back.
public string GetLine(string multiline,int line)
{
List<string> lines = new List<string>();
lines = multiline.Split('\n').ToList<string>();
return lines.Count >= line ? lines[line] : "";
}
I'm trying to remove any "new line" characters from each line of text in my log file.
Below is an example entry that I am reading in with a Stream Reader :-
<![LOG[Raising event:
[SMS_CodePage(850), SMS_LocaleID(2057)]
instance of SoftDistProgramStartedEvent
{
AdvertisementId = "000216F6";
ClientID = "GUID:B55C2757-CBAE-468E-B54F-46CAF2ECF68F";
CommandLine = "\"C:\\WINNT\\system32\\cscript.exe\" /nologo Shutdown_Desktops_Overnight.vbs";
DateTime = "20130211080211.784000+000";
MachineName = "DWD*****";
PackageName = "0000073C";
ProcessID = 2516;
ProgramName = "Shutdown Desktops Overnight";
SiteCode = "S00";
ThreadID = 3640;
UserContext = "NT AUTHORITY\\SYSTEM";
WorkingDirectory = "C:\\WINNT\\system32\\CCM\\Cache\\0000073C.1.System\\";
};
]LOG]!><time="08:02:11.800+000" date="02-11-2013" component="execmgr" context="" type="1" thread="3640" file="event.cpp:522">
In the actual Logfile this is displayed as one line in the file, with the "New Line Characters" replaced with a square.
I'm using the following code to read in the log entries :-
using (StreamReader sr = new StreamReader(#"C:\Documents and Settings\riversd\Desktop\Logfile2.log"))
{
string Line;
while ((Line = sr.ReadLine()) != null)
{
}
}
The issue is that when the StreamReader reads this entry from the txt file it breaks at :-
"<![LOG[Raising event:"
I need to remove all new line characters in this entry, on the fly. I don't want to read the entire file into memory and then remove them, I'd rather deal with each log as I read it.
Is it possible?
The call to Replace isn't working because of this detail from the MSDN doc of StreamReader.ReadLine:
A line is defined as a sequence of characters followed by a line feed ("\n"), a carriage return ("\r"), or a carriage return immediately followed by a line feed ("\r\n"). The string that is returned does not contain the terminating carriage return or line feed.
So if you're going to use StreamReader.ReadLine to read in the input, you could build up a new string with StringBuilder.Append (not AppendLine) as StreamReader.ReadLine implicitly removes the new line characters.
var filePath = "text.txt";
StringBuilder sb = new StringBuilder();
using (StreamReader reader = new StreamReader(filePath))
{
while (!reader.EndOfStream)
{
sb.Append(reader.ReadLine());
}
}
File.WriteAllText(filePath, sb.ToString());
sr.ReadLine().Replace(Environment.NewLine, String.Empty);
EDIT:
In case the end of line is not \r\n but \n you can use regex:
Line = Regex.Replace(sr.ReadLine(), #"(\r\n|\n)", String.Empty);
i dont know if anyone else was having exactly this issue.
here is the code i used to fix this issue.
using (System.IO.FileStream File = new System.IO.FileStream(e.FullPath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
{
using (System.IO.StreamReader Reader = new System.IO.StreamReader(File, Encoding.Default))
{
String CompleteData = Reader.ReadToEnd();
foreach (String Line in CompleteData.Split(new char[] { (char)13 }, StringSplitOptions.RemoveEmptyEntries))
{
if (Line.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)[0].Contains("Raising event"))
{
//Do Stuff
}
}
Reader.Close();
}
File.Close();
}
For some reason i had to do this because just using streamreader would throw an exception saying that the file is in use from another process.
It might help someone else at a later date..