Reading parameters from txt file in Forms skipping empty lines - c#

I have to read some parameters from a txt file and then use them in my Windows Forms application.
The txt file looks like this:
[Parameter1]
1
[Parameter2]
1000
[Parameter3]
5
[Parameter4]
0
I've been searching for the right solution on the Internet, but didn't find one. The point is to achieve these points:
1. There can be empty lines (for example 5 empty lines between 1 and [Parameter2] in the txt file and the app needs to load those parameters anyway.
2. If the txt file misses any of these parameters, the app needs to load existing ones and then I'll attribute the missing ones with default values.
Code in my app:
if (File.Exists("path.txt"))
{
FileStream fs = new FileStream("path.txt", FileMode.Open);
StreamReader sr = new StreamReader(fs);
string linia;
while ((linia = sr.ReadLine()) != null)
{
string a = string.Empty;
string b = string.Empty;
string c = string.Empty;
string LogLevelstring = string.Empty;
if (string.Compare(linia, "[Parameter1]") == 0)
a = sr.ReadLine();
if (string.Compare(sr.ReadLine(), "[Parameter2]") == 0)
b = sr.ReadLine();
if (string.Compare(sr.ReadLine(), "[Parameter3]") == 0)
c = sr.ReadLine();
if (string.Compare(sr.ReadLine(), "[Parameter4]") == 0)
LogLevelstring= sr.ReadLine();
}
fs.Close();
sr.Close();
}
This function loads line by line. When the .txt file is correct, it works, but when it has any of things i pointed above, it doesn't work.
Any help and code samples would be very appreciated. Thanks!

You could also try Regular Expresions using the Regex class to filter each row. It can shorten youre code a lot. If you need help to build youre regex try this website : https://regex101.com/.
Hope this helps :D
Jasper.

Related

Append Text at exact location in text

I was looking to append text to a exact location in a text file. I have used StreamReader to find the text in the file I am looking for. I thought about using StreamWriter but that obviously doesn't make sense. I was hoping to find some "append" method in some class somewhere that would help me do this but with now success. Or is there a better way to do this than to use StreamReader?
using (StreamReader sr = new StreamReader(fileName))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (line.Contains("VAR_GLOBAL CONSTANT"))
{
//append text before this variable
// e.g. (*VAR_GLOBAL CONSTANT
// append the (* before VAR_GLOBAL CONSTANT
}
if (line.Contains("END_VAR"))
{
//append text after this variable
// e.g. END_VAR*)
// append the *) after END_VAR
}
}
}
Does anyone have any thoughts on how to accomplish this?
One way to do it would be to read the file contents into a string, update the contents locally, and then write it back to the file again. This probably isn't very feasible for really large files, especially if the appending is done at the end, but it's a start:
var filePath = #"f:\public\temp\temp.txt";
var appendBeforeDelim = "VAR_GLOBAL CONSTANT";
var appendAfterDelim = "END_VAR";
var appendBeforeText = "Append this string before some text";
var appendAfterText = "Append this string after some text";
var newFileContents = File.ReadAllText(filePath)
.Replace(appendBeforeDelim, $"{appendBeforeText}{appendBeforeDelim}")
.Replace(appendAfterDelim, $"{appendAfterDelim}{appendAfterText}");
File.WriteAllText(filePath, newFileContents);

C# XML Father-Son update can not save

I'm trying to update an existing app.
I was asked previously to simply clean out an xml file for escape characters, which were coming to us, prior to them being pulled through to the company system. Doing this allowed us the option of avoiding writing inside an app written 7 years ago and working fine (but ZERO documentation)
It actually worked fine with
foreach (string d in Directory.GetFiles(test, "*.xml", SearchOption.AllDirectories))
{
String[] lines = File.ReadAllLines(d);
for (int i = 0; i < lines.Length; i++)
{
if (lines[i].Contains("&"))
{
i++;
}
//Replace incorrect characters
else if (lines[i].Contains("&"))
{
log.Info(saveName);
log.Error("Incorrect '&' Detected: Changing to '&'");
lines[i] = lines[i].Replace("&", "&");
log.Info(lines[i]);
}
}
System.IO.File.WriteAllLines(d, lines);
}
And maybe too easily as I have been asked to try to integrate this with the main app, to prevent the operators having to do the pre-clean.
I know (well I believe) that I am missing the corresponding System.IO.File.WriteAllLines(d, lines); in the following code but I can not get it or anything else to work.
The "replace" is working as the WriteLine is showing the corrected line(s) but I can not get the system to hold the changes.
MemoryStream ms = new MemoryStream();
ms.Position = 0;
List<string> rows = new List<string>();
using (var reader = new StreamReader(ms))
{
string line;
var sw = new StreamWriter(ms);
while ((line = reader.ReadLine()) != null)
{
if (line.Contains("&"))
{
Console.WriteLine(line);
line = line.Replace("&", "&");
sw.Write(line);
Console.WriteLine(line);
}
}
Not sure how important for you is to write a log, but seems you can do the same using something like this:
string text = File.ReadAllText("test.xml");
text = Regex.Replace(text, "&(?!amp;)", "&");
File.WriteAllText("test.xml", text);
It should also cover the case when there are more then one & symbol in one string (the original code will not handle it - so if the sting is something like '&hello&', it will be processed as '&hello&').
Lesson is "when amending a large app, make sure to read it all".
For some reason the original developer decided to dip back in to the zip file (where these files were received) and extract the whole thing again for the Stream.
Changed that and it all works and is running much faster as a result.

File in use error C# reading text from user specified file

My code is giving a runtime error that the file is in use already. I am not sure how I work around this. I need the file dialog to interact with the user but I want read through it line by line. the file is semicolon delimited and I parse it manually and feed it into the system. How can I release the file from opendialog so I can work with it. Any help much appreciated thanks in advance.
List<string> datalinestream = new List<string>();
FileDialog FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
TextReader reader = new StreamReader(FD.FileName);
using (reader)
{
string line = "";
while ((line = reader.ReadLine()) != null)
{
while (!string.Equals(reader.Read(),"/r"))
{
datalinestream.Add(GetWord(reader));
}
LuceneDB.AddUpdateLuceneIndex(new MATS_Doc( datalinestream));
datalinestream.Clear();
}
}
}
What I'd do is I will create a temporary file that contains the same information of the original text file. I will make sure to format the filename with something like a GUID so it will not cause any issues again. My code then will do all of the work on the temporary file.
Afterwards, (if you need to) update the original file with the changes that you did on the temporary file.
Working with files sometimes is a headache but workarounds or tricking the system does the job.
I would suggest separating out the FileOpenDialog interaction from the parsing.
Something like this:
List<string> datalinestream = new List<string>();
string fileName;
using(FileDialog FD = new System.Windows.Forms.OpenFileDialog())
{
if(FD.ShowDialog() == DialogResult.OK)
fileName = FD.FileName;
else
return;
}
TextReader reader = new StreamReader(fileName);
using (reader)
{
string line = "";
while ((line = reader.ReadLine()) != null)
{
while (reader.Read() != '\r')
{
datalinestream.Add(GetWord(reader));
}
LuceneDB.AddUpdateLuceneIndex(new MATS_Doc( datalinestream));
datalinestream.Clear();
}
}
I'm also assuming that you want to check for a \r character, instead of a string with the two characters / and r, as StreamReader.Read() returns a single character, otherwise your inner loop will have to change pretty drastically.

Displaying Text Content

Pretty simple one I hope. I have an article of text that I want to display in a window. Now rather than have this massive load of text in the centre of my code, can I add it as a Resource and read it out to the window somehow?
For those asking why, it's simply because it is a massive article and would be very ugly looking stuck in the middle of my code.
UPDATE FOR H.B.
I have tried a number of different approaches to this and am currently looking into the GetManifestResourceStream and using an embeddedResource (txt file) and writing that out to screen. Haven't finished testing it yet but if it works it would be a heck of a lot nicer than copying and pasting the entire text txtbox1.Text = "...blah blah blah".
_textStreamReader = new
StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("Problem.Explaination.txt"));
try
{
if (_textStreamReader.Peek() != -1)
{
txtBlock.Text = _textStreamReader.ReadLine();
}
}
catch
{
MessageBox.Show("Error writing text!");
}
My query remains, is there a better way of achieving this (assuming this is even successful)
Thanks
NOTE
In my example above I only want one line of text. If you were adapting this to read a number of lines from a file you would change it like so;
StreamReader _textStreamReader;
_textStreamReader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("Problem.Explaination.txt"));
var fileContents = _textStreamReader.ReadToEnd();
_textStreamReader.Close();
String[] lines = fileContents.Split("\n"[0]);
String[] lines2;
Int16 count;
foreach (string line in lines)
{
txtBlock.Text += line;
}
Add the file as a resource and, in your code, load it into a string.
StringBuilder sb = new StringBuilder();
using (var stream = this.GetType().Assembly.GetManifestResourceStream("MyNamespace.TextFile.txt"))
using(var reader = new StreamReader(stream))
{
string line;
while ((line = reader.ReadLine()) != null)
{
sb.AppendLine(line);
}
}
ViewModel.Text = sb.ToString();
You could place that text in a text file, and read it out in code
http://msdn.microsoft.com/en-us/library/db5x7c0d.aspx

How to read an entire file to a string using C#?

What is the quickest way to read a text file into a string variable?
I understand it can be done in several ways, such as read individual bytes and then convert those to string. I was looking for a method with minimal coding.
How about File.ReadAllText:
string contents = File.ReadAllText(#"C:\temp\test.txt");
A benchmark comparison of File.ReadAllLines vs StreamReader ReadLine from C# file handling
Results. StreamReader is much faster for large files with 10,000+
lines, but the difference for smaller files is negligible. As always,
plan for varying sizes of files, and use File.ReadAllLines only when
performance isn't critical.
StreamReader approach
As the File.ReadAllText approach has been suggested by others, you can also try the quicker (I have not tested quantitatively the performance impact, but it appears to be faster than File.ReadAllText (see comparison below)). The difference in performance will be visible only in case of larger files though.
string readContents;
using (StreamReader streamReader = new StreamReader(path, Encoding.UTF8))
{
readContents = streamReader.ReadToEnd();
}
Comparison of File.Readxxx() vs StreamReader.Readxxx()
Viewing the indicative code through ILSpy I have found the following about File.ReadAllLines, File.ReadAllText.
File.ReadAllText - Uses StreamReader.ReadToEnd internally
File.ReadAllLines - Also uses StreamReader.ReadLine internally with the additionally overhead of creating the List<string> to return as the read lines and looping till the end of file.
So both the methods are an additional layer of convenience built on top of StreamReader. This is evident by the indicative body of the method.
File.ReadAllText() implementation as decompiled by ILSpy
public static string ReadAllText(string path)
{
if (path == null)
{
throw new ArgumentNullException("path");
}
if (path.Length == 0)
{
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
}
return File.InternalReadAllText(path, Encoding.UTF8);
}
private static string InternalReadAllText(string path, Encoding encoding)
{
string result;
using (StreamReader streamReader = new StreamReader(path, encoding))
{
result = streamReader.ReadToEnd();
}
return result;
}
string contents = System.IO.File.ReadAllText(path)
Here's the MSDN documentation
For the noobs out there who find this stuff fun and interesting, the fastest way to read an entire file into a string in most cases (according to these benchmarks) is by the following:
using (StreamReader sr = File.OpenText(fileName))
{
string s = sr.ReadToEnd();
}
//you then have to process the string
However, the absolute fastest to read a text file overall appears to be the following:
using (StreamReader sr = File.OpenText(fileName))
{
string s = String.Empty;
while ((s = sr.ReadLine()) != null)
{
//do what you have to here
}
}
Put up against several other techniques, it won out most of the time, including against the BufferedReader.
Take a look at the File.ReadAllText() method
Some important remarks:
This method opens a file, reads each line of the file, and then adds
each line as an element of a string. It then closes the file. A line
is defined as a sequence of characters followed by a carriage return
('\r'), a line feed ('\n'), or a carriage return immediately followed
by a line feed. The resulting string does not contain the terminating
carriage return and/or line feed.
This method attempts to automatically detect the encoding of a file
based on the presence of byte order marks. Encoding formats UTF-8 and
UTF-32 (both big-endian and little-endian) can be detected.
Use the ReadAllText(String, Encoding) method overload when reading
files that might contain imported text, because unrecognized
characters may not be read correctly.
The file handle is guaranteed to be closed by this method, even if
exceptions are raised
string text = File.ReadAllText("Path"); you have all text in one string variable. If you need each line individually you can use this:
string[] lines = File.ReadAllLines("Path");
System.IO.StreamReader myFile =
new System.IO.StreamReader("c:\\test.txt");
string myString = myFile.ReadToEnd();
if you want to pick file from Bin folder of the application then you can try following and don't forget to do exception handling.
string content = File.ReadAllText(Path.Combine(System.IO.Directory.GetCurrentDirectory(), #"FilesFolder\Sample.txt"));
#Cris sorry .This is quote MSDN Microsoft
Methodology
In this experiment, two classes will be compared. The StreamReader and the FileStream class will be directed to read two files of 10K and 200K in their entirety from the application directory.
StreamReader (VB.NET)
sr = New StreamReader(strFileName)
Do
line = sr.ReadLine()
Loop Until line Is Nothing
sr.Close()
FileStream (VB.NET)
Dim fs As FileStream
Dim temp As UTF8Encoding = New UTF8Encoding(True)
Dim b(1024) As Byte
fs = File.OpenRead(strFileName)
Do While fs.Read(b, 0, b.Length) > 0
temp.GetString(b, 0, b.Length)
Loop
fs.Close()
Result
FileStream is obviously faster in this test. It takes an additional 50% more time for StreamReader to read the small file. For the large file, it took an additional 27% of the time.
StreamReader is specifically looking for line breaks while FileStream does not. This will account for some of the extra time.
Recommendations
Depending on what the application needs to do with a section of data, there may be additional parsing that will require additional processing time. Consider a scenario where a file has columns of data and the rows are CR/LF delimited. The StreamReader would work down the line of text looking for the CR/LF, and then the application would do additional parsing looking for a specific location of data. (Did you think String. SubString comes without a price?)
On the other hand, the FileStream reads the data in chunks and a proactive developer could write a little more logic to use the stream to his benefit. If the needed data is in specific positions in the file, this is certainly the way to go as it keeps the memory usage down.
FileStream is the better mechanism for speed but will take more logic.
well the quickest way meaning with the least possible C# code is probably this one:
string readText = System.IO.File.ReadAllText(path);
you can use :
public static void ReadFileToEnd()
{
try
{
//provide to reader your complete text file
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line = sr.ReadToEnd();
Console.WriteLine(line);
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
string content = System.IO.File.ReadAllText( #"C:\file.txt" );
You can use like this
public static string ReadFileAndFetchStringInSingleLine(string file)
{
StringBuilder sb;
try
{
sb = new StringBuilder();
using (FileStream fs = File.Open(file, FileMode.Open))
{
using (BufferedStream bs = new BufferedStream(fs))
{
using (StreamReader sr = new StreamReader(bs))
{
string str;
while ((str = sr.ReadLine()) != null)
{
sb.Append(str);
}
}
}
}
return sb.ToString();
}
catch (Exception ex)
{
return "";
}
}
Hope this will help you.
you can read a text from a text file in to string as follows also
string str = "";
StreamReader sr = new StreamReader(Application.StartupPath + "\\Sample.txt");
while(sr.Peek() != -1)
{
str = str + sr.ReadLine();
}
I made a comparison between a ReadAllText and StreamBuffer for a 2Mb csv and it seemed that the difference was quite small but ReadAllText seemed to take the upper hand from the times taken to complete functions.
I'd highly recommend using the File.ReadLines(path) compare to StreamReader or any other File reading methods. Please find below the detailed performance benchmark for both small-size file and large-size file.
I hope this would help.
File operations read result:
For small file (just 8 lines)
For larger file (128465 lines)
Readlines Example:
public void ReadFileUsingReadLines()
{
var contents = File.ReadLines(path);
}
Note : Benchmark is done in .NET 6.
This comment is for those who are trying to read the complete text file in winform using c++ with the help of C# ReadAllText function
using namespace System::IO;
String filename = gcnew String(charfilename);
if(System::IO::File::Exists(filename))
{
String ^ data = gcnew String(System::IO::File::RealAllText(filename)->Replace("\0", Environment::Newline));
textBox1->Text = data;
}

Categories

Resources