Using commands in a text file - c#

I am looking to use a text file to make a really basic way of controlling a robot
To do this I would like the have a txt file like below
move #1 P1453 #5 p983 T2000
wait 2000
If I could read each line and use the first word to decide what to do with the data following it. I would need to be able to serial.wrightline the Text following the word move and use the word wait to pause the program in milliseconds. I have found how to read each line of a file but am unaware of how to
separate the word's at the start of the line so i can just use the data following

I don't understand this part:
I have found how to read each line of a file but am unaware of how to
separate the word's at the start of the line
This is how I do this:
StreamReader sr = new StreamReader("file1.txt");
while ( !sr.EndOfStream )
{
string line = sr.ReadLine();
string[] parts = line.Split(' ');
string command = parts[0].Trim();
//Use parts[x] where x > 0 to extract other items of the line
}

Related

Best approach to replace specific lines in a text file in c#

For the following operation:
Open a text file
Search and replace all searching characters with new characters
I'd like to achieve above in c#, here is my code:
using (StreamReader sr = new StreamReader(#"S:\Personal Folders\A\TESTA.txt"))
{
using (StreamWriter sw = new StreamWriter(#"S:\Personal Folders\A\TESTB.txt"))
{
string line;
while ((line = sr.ReadLine())!= null)
{
if (!line.Contains("before"))
{
sw.WriteLine(line);
}
else if (line.Contains("before"))
{
sw.WriteLine(line.Replace("before", "after"));
}
}
}
}
Basically, the above code will generate a new file with the desired replace operation, but as you can see, the way I am doing is read each line of the original file and write to a new file. This could achieve my goal, but it may have system IO issue because it is reading and writing for each line. Also, I cannot read all the lines to an array first, and then write, because the file is large and if I try to write to an string[], replace all, then write the array to the file, will bring about the memory timeout issue.
Is there any way that I can just locate to the specific lines, and just replace those lines and keep all the rest? Or What is the best way to solve the above problem? Thanks
I don't know what IO issue you are worried about, but your code should work ok. You can code more concisely as follows:
using (StreamReader sr = new StreamReader(#"S:\Personal Folders\A\TESTA.txt"))
{
using (StreamWriter sw = new StreamWriter(#"S:\Personal Folders\A\TESTB.txt"))
{
while ((string line = sr.ReadLine())!= null)
{
sw.WriteLine(line.Replace("before", "after"));
}
}
}
This will run a bit faster because it searches for "before" only once per line. By default the StreamWriter buffers your writes and does not flush to the disk each time you call WriteLine, and file IO is asynchronous in the operating system, so don't worry so much about IO.
In general, what you are doing is correct, possibly followed by some renames to replace the original file. If you do want to replace the original file, you should rename the original file to a temporary name, rename the new file to the original name, and then either leave or delete the original file. You must handle conflicts with your temporary name and errors in all renames.
Consider you are replacing a six character string with a five character string - if you write back to the original file, what will you do with the extra characters? Files are stored on disk as raw bytes of data, there is no "text" file on disk. What if you replace a string with a longer one - you then potentially have to move the entire rest of the file to make room to write the longer line.
You can imagine the file on disk as letters written on graph paper in the boxes. The end of each line is noted by a special character (or characters - in Windows, that is CRLF), the characters fill all the boxes horizontally. If you tried to replace words on the graph paper you would have to erase and re-write lots of letters. Writing on a new sheet will be easiest.
Well, your approach is basically fine... but I wouldn't check if the line contains the word before... the trade-off is not good enough:
using (StreamReader sr = new StreamReader(#"S:\Personal Folders\A\TESTA.txt"))
{
using (StreamWriter sw = new StreamWriter(#"S:\Personal Folders\A\TESTB.txt"))
{
String line;
while ((line = sr.ReadLine()) != null)
sw.WriteLine(line.Replace("before", "after"));
}
}
Try following :
else if (line.Contains("before"))
{
sw.WriteLine(line.Replace("before", "after"));
sw.Write(sr.ReadToEnd());
break;
}

Get all lines after the last print of line with 'keyword' in C#

I am working on a c# project.
I am trying to send a logfile via email whenever application gets crashed.
however logfile is a little bit larger in size.
So I thought that i should include only a specific portion of logfile.
For that I am trying to read all the lines after the last instance of line with specified keyword.(in my case "Application Started")
since Application get restarted many times(due to crashing), 'Application Started' gets printed many times in file. So I would only want last print of line containing 'Application Started' & lines after that until end of file.
I require help to figure out how can i do this.
I have just started with Basic code as of now.
System.IO.StreamReader file = new System.IO.StreamReader("c:\\mylogfile.txt");
while((line = file.ReadLine()) != null)
{
if ( line.Contains("keyword") )
{
}
}
Read the file, line-by-line, until you find your keyword. Once you find your keyword, start pushing every line after that into a List<string>. If you find another line with your keyword, just Clear your list and start refilling it from that point.
Something like:
List<string> buffer = new List<string>();
using (var sin = new StreamReader("pathtomylogfile"))
{
string line;
bool read;
while ((line = sin.ReadLine())!=null)
{
if (line.Contains("keyword"))
{
buffer.Clear();
read = true;
}
if (read)
{
buffer.Add(line);
}
}
// now buffer has the last entry
// you could use string.Join to put it back together in a single string
var lastEntry = string.Join("\n",buffer);
}
If the number of lines in each entry is very large, it might be more efficient to scan the file first to find the last entry and then loop again to extract it. If the whole log file isn't that large, it might be more efficient to just ReadToEnd and then use LastIndexOf to find the start of the last entry.
Read everything from the file and then select the portion you want.
string lines = System.IO.File.ReadAllText("c:\\mylogfile.txt");
int start_index = lines.LastIndexOf("Application Started");
string needed_portion = lines.Substring(start_index);
SendEmail(needed_portion);
I advise you to use a proper logger, like log4net or NLogger.
You can configure it to save to multiple files - one containing complete logs, other containing errors/exceptions only. Also you can set maximum size of log files, etc. Or can configure them to send you a mail if exception occours.
Of course this does not solves your current problem, for it there is some solution above.
But I would try simpler methods, like trying out Notepad++ - it can handle bigger files (last time i've formatted a 30MB XML document with it, it took about 20 mins, but he did it! With simple text files there should be much better perf.). Or if you open the file for reading only (not for editing) you may get much better performance (in Windows).

read the second line from the text

how do i read the second line of text in visual studio 2012 c#
the txt file
user123
**12345**
asdfd
i want to get the second line in one button1_click and show it to textblock2
i did try learn from here
How do I read a specified line in a text file?
and here
How to skip first line and start reading file from second line in C#
but no one of these works because theres difference i couldnt apply in my code
any help?
=================================================================================
sorry to confusing you all
actually im really lacking experience in programming and i hardly know how to use it
right now im using vs2012 in windows8 , is that mean i was coding in winrt?
btw , i appreciate all your help and successfully applying answer to my code
this is the actual code
var file = await ApplicationData.Current.LocalFolder.GetFileAsync(tb1.Text+".txt");
var line = await FileIO.ReadLinesAsync(file);
if (tb2.Text == line[2])
{
tb3.Text = (line[1]);
}
var desiredText = File.ReadLines("C:\myfile.txt").ElementAt(1);
File.ReadLines() returns an String[] of the lines in a file. The index of the second line is 1. See this.
try
var desiredText = File.ReadLines("C:\myfile.txt");
textbox1.text = desiredText[1];
Just call a .ReadLine() before you start capturing the content of the file.
Essentially this will make the reader skip the first line of the file and take only the 2nd line and all lines that follow it.
// Try this to take the second line.
string line;
using (var file_read = new StreamReader(your_file))
{
file_read.ReadLine();
line = file_read.ReadLine();
}
textBox1.Text = line.ToString();

WP7 Isolated Storage Text Document Read Line

Is there a way using Isolated storage ie a Text document, to grab the text on a certain line.
I would like to save variables to a text document on my settings page of my app. Then go back to the main page and read the variable saved on line 3. I already know how to save them. just not read certain lines.
Also is the text document created by my app going to still be there if i close and reopen the app?
Try this
using( TextReader reader = new StreamReader(
new IsolatedStorageFileStream( "myFile.txt", System.IO.FileMode.Open,
IsolatedStorageFile.GetUserStoreForApplication() ) ) {
string line = reader.ReadLine(); // first line, discard
line = reader.ReadLine(); // second line, discard
line = reader.ReadLine(); // third line, read the variable value
}
However, you might be better off using the IsolatedStorageSettings class to store settings (the link contains example usage). Another option is to put all your settings into a serializable class and use an XmlSerializer to save / read the settings. Both these approaches would not require parsing the file manually.

How to compare two TXT files before send it to SQL

I have to handle TXT dat files which coming from one embed device, My problem is in that device always sending all captured data but I want to take only difrences between two sending and do calculation on them. After calculation I send it to SQL using bulkinsert function. I want to extract data which is different according to first file I got from device. Lats say that device first time device send data like this in some.dat (ASCII) file
0000199991
0000199321
0000132913
0000232318
0000312898
On second calls to get data from device it is going to return all again (previous and next captured records) something like this
0000199991
0000199321
0000132913
0000232318
0000312898
9992129990
8782999022
2323423456
But this time I do want only to calculate and pass trough data added after first insert.
I am trying to make Win Forms app using C# and Visual Studio 2008
You can do this using LINQ:
string[] addedLines = File.ReadAllLines(secondPath)
.Except(File.ReadAllLines(firstPath))
.ToArray();
Note that this will be slow for large files.
For large files, replace ReadAllLines with the following method: (In .Net 4, you can use File.ReadLines instead)
static IEnumerable<string> EnumerateLines(string path) {
using(var reader = File.OpenText(path)) {
string line;
while(null != (line = reader.ReadLine())
yield return line;
}
}
Would this work for you?
string dataAddedAfterFirstInsert = secondString.SubString(firstString.Length, secondString.Length)
One option would be to remember the filesize each time you receive the file, then when you get the new file you can immediately move the file pointer to the position in the file that corresponds to the end of the previous file and read from that point on.
Here is a rough outline of the idea
long lastPosition = GetLastFilePositionFromDatabase();
using (FileStream fs = new FileStream(...))
{
// Seek to the last position, this is zero the first time
fs.Seek(lastFilePosition, SeekOrigin.Begin);
// Process your file from the current position
ProcessFile(fs);
// Once you reach the end of the file, save this position so
// for use with the next file
SaveLastFilePositionToDatabase(fs.Position);
}

Categories

Resources