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
Related
The following code line allows me to append the variable w1 in excel file. but appending process happens in the first column. how to make it for multi-variables {w1, w2, w3} in multi-columns?
File.AppendAllText(Path.Combine(docPath, "Groupbox1.CSV"), w1);
First, you're actually working with .CSV files, not Excel. The CSV stands for Comma Separated Values, so each value in a line of text on these files are typically separated by a comma (or other delimiters such as semicolon). The Excel application lets you open .CSV files, but they are different from Excel files which have either .xls or .xslx extensions. Excel will display values separated by commas in their own columns.
Then, say you have multiple variables. Then you can simply create one string with commas in between values, and write it to the file.
var w1 = "Data1";
var w2 = "Data2";
var w3 = "Data3";
// This creates a string, according to above data, that looks like
// "Data1,Data2,Data3"
var lineToWrite = string.Format("{0},{1},{2}", w1, w2, w3);
File.AppendAllText(Path.Combine(docPath, "Groupbox1.CSV"), lineToWrite);
Now we write that line to the file, and each data item is separated by a comma. Now when you open this with Excel, each data item will be displayed in its own column.
I am creating an application which converts a MS Access table and an Excel sheet to .csv files and then differences the access table with the excel sheet. The .csv files are fine but the resulting difference file has errors in fields that contain html (the access table has fields with the html). I'm not sure if this is a special character issue because the special characters were not an issue in creating the .csv file in the first place, or if it is an issue with the way I am differencing the two files.
Part of the problem I suppose could be that in the access .csv file, the fields that contain the html are formatted so that some of the information is on separate lines instead of all on one line, which could be throwing off the reader, but I don't know how to correct this issue.
This is the code for creating the difference file:
string destination = Form2.destination;
string path = Path.Combine(destination, "en-US-diff.csv");
string difFile = path;
if (File.Exists(difFile))
{
File.Delete(difFile);
}
using (var wtr = new StreamWriter(difFile))
{
// Create the IEnumerable data sources
string[] access = System.IO.File.ReadAllLines(csvOutputFile);
string[] excel = System.IO.File.ReadAllLines(csvOutputFile2);
// Create the query
IEnumerable<string> differenceQuery = access.Except(excel);
// Execute the query
foreach (string s in differenceQuery)
{
wtr.WriteLine(s);
}
}
Physical line versus logical line. One solution is to use a sentinel, which is simply an arbitrary string token selected in such a way so as not to confound the parsing process, for example "##||##".
When the input files are created, add the sentinel to the end of each line...
1,1,1,1,1,1,###||##
Going back to your code, the System.IO.File.ReadAllLines(csvOutputFile); uses the Environment.Newline string as its sentinel. This means that you need to replace this statement with the following (pseudo code)...
const string sentinel = "##||##";
string myString = File.ReadAllText("myFileName.csv");
string[] access = myString.Split(new string[]{sentinel},
StringSplitOptions.RemoveEmptyEntries);
At that point you will have the CSV lines in your 'access' array the way you wanted as a collection of 'logical' lines.
To make things further conformant, you would also need to execute this statement on each line of your array...
line = line.Replace(Environment.NewLine, String.Empty).Trim();
That will remove the culprits and allow you to parse the CSV using the methods you have already developed. Of course this statement could be combined with the IO statements in a LINQ expression if desired.
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.
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);
I am working on a desktop application develop in C#. what i want to do is to:
Open a text file(.txt) Read Data Line By Line Create a grid type structure(i.e combination of
horizontal and vertical line) Then take first line and display its each char in single cell And the take second line and display its each char in single cell and so on.
Since i am beginner so i don't have any idea that how to acheive this. I only want some suggestions and guidance.
Well, this is actually easy to do provided you compose the correct items together to get your result.
You'll want to look up File operations, string manipulation (as well as the knowledge that a string is nothing but an enumerable of chars), and then some simple looping to get what you want.
At a high level, you'll just be needing to get the math right to display your set of text as a grid in X columns by Y rows.
Use File.ReadAllLines(). It will give you and array of strings - line by line.
For each string returned by ReadAllLines use string.ToCharArray. It will give you an array of symbols in string.
Update:
Number of columns in grid will be equal to max length of char array. Number of rows - to number of lines. Hope, I understood your task correctly.
Sounds like a homework problem?
Use the File class to read your text file. As far as printing the output to the screen, you have many options...if you're building a console application the you could just write characters to the output using the Console methods.
Hint: to split each line of text into characters, use the ToCharArray() method on the String class.
here is how you can read from a text file line by line
int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
Console.WriteLine (line);
counter++;
}
file.Close();
// Suspend the screen.
Console.ReadLine();
http://msdn.microsoft.com/en-us/library/aa287535(v=vs.71).aspx