Editing specific lines in a text file using c# - c#

I'm currently trying to edit a text file in c#. This text file is created in a previous form and consists of the following :
Date Of Birth = 01/01/1980
Age = 31
Total = 40985
required1 =
required2 =
required3 =
This text file is only 13 lines long, basically i want to ignore the first three lines then edit the following 10 lines. I tried initially with the following code but the obvious flaw is appending to the file:
List<string> newlines = new List<string>();
newlines.Add(Convert.ToString(required1));
newlines.Add(Convert.ToString(required2));
newlines.Add(Convert.ToString(required3));
System.IO.File.AppendAllLines(filepath);
I'm thinking using streamreader reading all the lines but how to edit the 3rd line onwards is something of a mystery, yes I'm new using c# any help is greatly appreciated.

Since your file is small, you can load it whole into memory. Then work with that and save it, completely overwriting the whole file:
string[] lines = File.ReadAllLines(fileName);
// modify the lines
File.WriteAllLines(fileName, lines);

Related

CSV file double-spacing lines

I am having trouble with OpenOffice Calc opening a CSV file that I create using StreamWriter C#. When it opens it has empty lines between every line that should be there(double-spaced). There seems to be some kind of doubling of the carriage returns. When I open it in Notepad it reads correctly. When I changed the program to write integers instead of strings the problem went away. It seems to be adding a return on the end of each string and then the formating adds another return that I'm not seeing.
Output looks like this...
1...
2...
3...
Output should look like this...
1...
2...
3...
Here is the ForEach loop I use to write the List to file...
using (StreamWriter sw = new StreamWriter(#"c:\andy\Arduino StreamWriter.csv", false, Encoding.UTF8))
{
foreach (string element in SerialPortString)
{
sw.WriteLine(element);
}
}
There is only one field of data per line, so there are no delimiters, just new lines. I tried formatting so that it would write with quotes around each field hoping that would eliminate confusion for the CSV format, but I wasn't able to figure that out either.
Any help would be appreciated.
Thanks.
Change
sw.WriteLine(element);
to
sw.WriteLine(element.Trim());
or maybe
sw.WriteLine(element.TrimEnd());
Trim the element first. That will remove any LineFeeds or other whitespace characters around the 'edges' of the characters. Then the StreamWriter's CRLFs will be the only newlines present.

C# trouble creating a table in console

I'm struggle to get data to display in a table within a console application. I believe it may be something to-do with the way I am getting the data to display.
I'm using this to read the content of text files:
string currentDir = Directory.GetCurrentDirectory();
string[] textFiles = Directory.GetFiles(currentDir, "*.txt");
string[] lines = new string[11];
for (int i = 0; i < textFiles.Length; i++)
{
lines[i] = File.ReadAllText(textFiles[i]);
}
Then I'm trying to display all the content of the text file into a table, each text file has 600 entries and they all go together to make a table.
Console.WriteLine("{0,10} \t {1,15}", lines[0], lines[1]);
Was my attempt of getting them to display in a table but only the last entry of lines[0] and first entry of lines[1] are being put on the same line in console... Anyone have any ideas?
You're reading the entire contents of a file in a simple string, so that's what you'll get in that string - the contents of the file, including any new lines, tabs, spaces and so on. If you want to manipulate individual bits of strings within those files, you'll need to split those strings according to some rules first.
The formatting alignment you're using doesn't do all that much by itself - see Alignment Component in https://msdn.microsoft.com/en-us/library/txafckwd.aspx

.txt file to .xlsx file (600 rows and 40 columns)

I have a program that combines three text files and put them all into one and sorts them all out alphabetically. I was wondering how I could possibly put this onto an excel spreadsheet without downloading and using the excellibrary (if that's possible).
Heres my code that combines all three files if that helps.
private void button1_Click(object sender, EventArgs e) // merge files button
{
System.IO.StreamWriter output = new System.IO.StreamWriter("OUTPUT.txt");
String[] parts = new String[1000];
String[] parts2 = new String[1000];
parts = File.ReadAllLines(textBox1.Text); //gets filepath from top textbox
parts2 = File.ReadAllLines(textBox2.Text); //gets filepath from middle textbox
String[] head = File.ReadAllLines(headingFileBox.Text); //header file array
//merging the two files onto one list, there is no need to merge the header file because no math is being
//computed on it
var list = new List<String>();
list.AddRange(parts);
list.AddRange(parts2);
//foreach loop to write the header file into the output file
foreach (string h in head)
{
output.WriteLine(h);
}
//prints 3 blank lines for spaces
output.WriteLine();
output.WriteLine();
output.WriteLine();
String[] partsComb = list.ToArray(); // string array that takes in the list
Array.Sort(partsComb);
//foreach loop to combine files and sort them by 1st letter
foreach (string s in partsComb)
{
partsComb.Equals(s);
output.WriteLine(s);
}
output.Close();
}
Any help would be much appreciated.
You could look at creating it in a CSV format (Comma-separated values). Excel naturally opens it up and loads the data into the rows and cells.
Basic CSV looks like this:
"Bob","Smith","12/1/2012"
"Jane","Doe","5/10/2004"
Some things are optional like wrapping everything in quotes, but needed if your data may contain the delimiter.
If you're okay with a comma separated values (CSV) file, that's easy enough to generate with string manipulation and will load in Excel. If you need an excel specific format and are okay with XLSX, you can populate one with some XML manipulation and a ZIP library.
Fair warning, you will have to be careful about escaping commas and new lines if you choose a traditional CSV file. There are libraries that handle that as well.
You might want to try Excel package plus: http://EPPlus.codeplex.com
It's free, lightweight, and can create xlsx files.

Reading specific number of lines from text file in c#

I'm using the following StreamReader to read from text file
string temp = fs.ReadToEnd ();
readlines[i] = temp;
I want to read a specific number of lines from the text file (let we say, from line number 1 until line number 300 only), then write the lines into one element of array. Could anyone help please? thanks in advance.
If you want to skip n first lines and read p lines from there :
var lines = System.IO.File.ReadLines(path).Skip(n).Take(p).ToArray()
Tried with a simple text file.
var lines = File.ReadLines("yourfile").Take(300);
readlines[i] = string.Join("-", lines);
Use the ReadLine method and add a counter and increase it by line and when you hit 300 do a break out of the loop

LINQ; Select Groups of Lines from a Text File

Greeting Gurus, I have a text file with groups of text that I need to seperate into seperate string arrays. How do I group these using the line "start:" as the delimiter? (groups may contain differing line counts but the all begin with "start:". Is this a job that LINQ can accomplish? (Each line has seperate data, it does not look that way in the preview).
List<string> lines = File.ReadAllLines(#"C:\test.txt").ToList();
start: data 1
boy: data 2
great: data 3
start: data 7
boy: data 8
great: data 9
girl: data 10
may be there is a linq solution but when you simply can handle this with for loops, I think there isn't any need to linq, for example I think bellow code done what you want:
var groups = new List<List<string>>();
foreach (var line in lines)
{
if (line.StartsWith("Start:"))
{
groups.Add(new List<string>());
}
groups[groups.Count - 1].Add(line);
}
I'd assumed first line of your file starts with Start: else you should skip first lines until reach the first start:.
File.ReadAllText(#"C:\test.txt").split("start:");
Will read the file and split the file into an aray of string on the start: tag.

Categories