Read text file line by line in C# - c#

I am trying to read a text file line by line inside a textbox, but it returns only the word "!MANAGERS" in the textbox.
My text file is:
!MANAGERS
NUMBERS = 6
ADMIN = 1
!INFORMATIONS
741852:PAULO MARCO:MANAGER:TEAM
My code to get the file is:
public static string GetFile () {
string filepath = #"C:\Files\projectmanager.txt";
StreamReader reader = new StreamReader (filepath);
string lines = reader.ReadLine ();
var list = new List<string> ();
list.Add (lines);
string[] liness = list.ToArray ();
foreach (string line in liness) {
return line;
}
return "ERROR";
}
My textbox code is:
String filetext = ToolLibrary.FileSystem.GetFile();
textbox1.Text = filetext;

If this is an option for you, this can be done in one line provided you have set Multiline to true on your textbox properties.
textbox1.Lines = System.IO.File.ReadAllLines(#"C:\Files\projectmanager.txt");

You can simply write
textbox1.Text = File.ReadAllText(filepath);
Also, set the Multiline property of the text box to true. (You can do so in the properties window.)

Related

C# Read From Text File, New Line

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

Delete last line of file, when using the data to draw a chart c#

I am in a trouble, when I am trying to delete the last line of my csv file, when I'm trying to draw a chart of the data.
My file contains a lot of data, which I get through the following code:
public void StreamOpen()
{
Stream stream;
OpenFileDialog getDialog = new OpenFileDialog();
getDialog.Filter = "csv File|*.csv";
getDialog.Title = "Get a .csv file";
if (getDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if ((stream = getDialog.OpenFile()) != null)
{
strFileName = getDialog.FileName;
string[] filetext = File.ReadAllLines(strFileName);
}
stream.Flush();
}
}
public void OpenFile()
{
if (!File.Exists(strFileName))
{
ListA();
ListB();
}
if (strFileName != null)
{
var reader = new StreamReader(File.OpenRead(strFileName));
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(';');
UpdateChart();
listA.Add(values[0]);
listB.Add(values[1]);
}
}
ListA();
ListB();
}
The problem is, that in the last line of my file, I save a text like
"Count of movements" + value
, and this value I want to skip when drawing that chart, instead I want to show that value in a textbox.
Now a error occur, that listA and listB is not the same, and I see why, because that last line is taken as a part of listA.
Hope you can help me to delete that last line, and help me to show how to save that value in a textbox.
Output in textfile:
09:03:28 ; 0
09:03:29 ; 1
09:03:30 ; 0
09:03:31 ; 0
Count of movements 2
Change your code to this
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (line.StartsWith("Count"))
break;
/....
}
Skip if last line starts with certain string
What about this approach:
string[] values = line.Split(';');
if(values.Length != expected_column_count) // then ignore
Edit
Or if something other is special about the unwanted line, for example it always starts with the same text:
if(line.StartsWith(unwanted_prefix)) // then ignore

IoException while writing in text file in c#

I have text file which i need to update according to the regex match but as soon as my program tries to write a line into text file it is giving following error..
The process cannot access the file 'D:\Archieve\20140123.text' because it is being used by another process.
Here is my C# code..
static void Main(string[] args)
{
string textfilename="";
string strDateTime = DateTime.Now.ToString("yyyyMMdd");
string strformatedatetime = DateTime.Now.ToString("yyyy/MM/dd");
if (strDateTime != "") {
string loc = "D:\\Archieve\\";
string date=strDateTime;
string text=".text";
textfilename = loc + date + text;
File.Create(textfilename);
}
string pattern = "^" + strformatedatetime + ".*";
string FileToCopy = "D:\\ipdata.txt";
string NewCopy =textfilename;
StringBuilder sb = new StringBuilder("");
List<string> newLines = new List<string>();
if (System.IO.File.Exists(FileToCopy) == true)
{
string[] lines = File.ReadAllLines(FileToCopy);
foreach (string line in lines)
{
if (Regex.IsMatch(line, pattern))
{
sb.Append(line + System.Environment.NewLine);
TextWriter tsw = new StreamWriter(textfilename,true);
//Writing text to the file.
tsw.WriteLine(sb);
//Close the file.
tsw.Close();
}
}
}
}
I am getting above defined error at this line of code...
TextWriter tsw = new StreamWriter(textfilename,true);
Where am i going wrong ?
You don't need to have a separate instruction to create a file.
The StreamWriter will take care of it: Here is the description of the constructor you user
> Initializes a new instance of the StreamWriter class for the specified
> file by using the default encoding and buffer size. If the file
> exists, it can be either overwritten or appended to. If the file does
> not exist, this constructor creates a new file.
Use File.Create(textfilename).Close();
As the error message suggests

Extract data from text file

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

C# windows forms application:How can I replace a single line in a textfile without deleting the original file?

I am making a project that uses streamreader and streamwriter, Is it possible that I only replace or save a text in an specific line only without affecting the other lines?
if I make like this
streamreader sr = new streamreader(#"txtfile");
list<string> lines = new list<string>();
while (!sr.EndOfStream)
sr.readline();
{
lines.Add(sr.ReadLine();
}
//put in textbox
sr.close();
{
streamwriter sw = new streamwriter(#"txtfile");
sw.WriteLine(textBox1.text);
sw.close();
}
this is just a sample, but Is it possible that I use list also un streamwriter?
If you want a one line solution (code golf :) ) you can use
string path = #"C:\Test.txt";
string lineToReplace = "Relpace This Line";
string newLineValue = "I Replaced This Line";
File.WriteAllLines(path, File.ReadAllLines(path).Select(line => line.Equals(lineToReplace) ? newLineValue : line));
You cannot just change a line as such but you can to ReadAllLines, find the line you want to change, change it and write all of it to the file again :
StringBuilder newFile = new StringBuilder();
string temp = "";
string[] file = File.ReadAllLines(#"txtfile");
foreach (string line in file)
{
if (line.Contains("string you want to replace"))
{
temp = line.Replace("string you want to replace", "New String");
newFile.Append(temp + "\r\n");
continue;
}
newFile.Append(line + "\r\n");
}
File.WriteAllText(#"txtfile", newFile.ToString());
Read the file into memory, changing the line(s) you want to change, close the reader, open the file for writing, write the new contents of the file out.

Categories

Resources