Export c# array to csv file with title - c#

I tried to export an 2-D array from c# to a csv file but last several rows are missing in the csv file.I don't know where the problem is in my code.
First,I'd like to know if my code is not correct?
Second,is it possible to add a title for each row in the csv file .
Thanks in advance
Here is an example of my array in c#
string[,] array=new string[]{{2000,2},{2001,4}}
I want to a result like this in csv file with title
Date C1
2000 2
2001 4
My code:
var outfile=new.streamwriter(#"fileadress.csv");
for(int i=0;i<array.GetUpperbound(0);i++)
{
string content="";
for(int j=0;j<array.GetUpperbound(1);j++)
{
content+= array[i,j]+";";
}
outfile.WriteLine(content);
}

There are a lot of problems in the code shown. The most important is the wrong usage of GetUpperBound that return the 'upperbound' of your array, and your example this upperbound is 1 (not 2) thus the < array.UpperBound skips the last position in the array.
I suggest a reworking of your code in this way
// This is an array of strings right?
string[,] array=new string[,]{{"2000","2"},{"2001","4"}};
// Use a StringBuilder to accumulate your output
StringBuilder sb = new StringBuilder("Date;C1\r\n");
for (int i = 0; i <= array.GetUpperBound(0); i++)
{
for (int j = 0; j <= array.GetUpperBound(1); j++)
{
sb.Append((j==0 ? "" : ";") + array[i, j]);
}
sb.AppendLine();
}
// Write everything with a single command
File.WriteAllText(#"fileadress.csv", sb.ToString());

Related

Reading a file and storing in 2d array on Form Load

I'm designing a simple Epos system as a project and I need to read my stock values in from a file at the beginning of the application in the form of a collection so I am trying to use a 2d int array but not having much luck.
The format of my txt file looks like this:
15,10,12,19,8
16,9,11,17,10
7,6,17,14,11
8,8,12,13,5
6,7,13,14,4
1,4,15,10,10
6,9,10,14,13
8,7,9,10,11
8,12,10,15,6
9,7,6,13,9
18,8,7,11,5
7,12,10,8,9
12,6,7,9,10
My code is as follows :
private void ReadToFileOpeningStock(int [,] Stock)
{
//create an array to hold data from file
string[] OneRowOfDataArray;
const int StockColumns = 13;
const int StockRows = 5;
int[,] STOCK_ITEMS = new int[StockColumns, StockRows];
try
{
// Declare a StreamReader variable.
StreamReader inputFile;
// Open the file and get a StreamReader object.
inputFile = File.OpenText("Opening StartingStock.txt");
while (!inputFile.EndOfStream)
{
OneRowOfDataArray = inputFile.ReadLine().Split(',');
for (int i = 0; i < StockColumns; i++)
{
//Here are the inner columns
for (int j = 0; j < StockRows; j++)
{
}
}
}
inputFile.Close();
}
catch
{
MessageBox.Show("Error");
}
I also have an empty array named Stock declared with the rest of thevariables that I have declared in the method name above.
int[,] Stock ;
How do I assign my text values to an array so that I can use it later in the application?
Sorry if I'm not being clear, I'm new to programming. Any help would be greatly appreciated. Thanks.
I changed it to use file.readallines as it is what I normally use. I've added an extra array to record all the lines, to then be separated with a split into OneRowOfDataArray.
I added outputs and the line to set the value to the STOCK_ITEMS. The only other thing I changed is I removed the spaces in between the rows on the txt file
static int[,] STOCK_ITEMS = new int[4, 3];
static void Main(string[] args)
{
//create an array to hold data from file
string[] RowsOfData;//contains rows of data
string[] OneRowOfDataArray;//will contain values seperated by the rows
const int StockColumns = 13;
const int StockRows = 5;
int[,] STOCK_ITEMS = new int[StockColumns, StockRows];
try
{
// Open the file and get a StreamReader object.
RowsOfData = File.ReadAllLines("Opening StartingStock.txt");//sets all lines and seperates them into ROWSOFDATA array
for (int i = 0; i < StockColumns; i++)
{
OneRowOfDataArray = RowsOfData[i].Split(',');//splits the values in each row seperate
Console.WriteLine();//new line when outputting the data
//Here are the inner columns
for (int j = 0; j < StockRows; j++)
{
STOCK_ITEMS[i, j] = Int32.Parse(OneRowOfDataArray[j]);//save to correct index in stock items
Console.Write("[" + STOCK_ITEMS[i, j] + "]");//output value from the row
}
}
}
catch
{
MessageBox.Show("Error");
}
}
txt file
15,10,12,19,8
16,9,11,17,10
7,6,17,14,11
8,8,12,13,5
6,7,13,14,4
1,4,15,10,10
6,9,10,14,13
8,7,9,10,11
8,12,10,15,6
9,7,6,13,9
18,8,7,11,5
7,12,10,8,9
12,6,7,9,10

C# Cannot use Streamwriter on a txt file in C# Properties.Resources

I am currently working on an assignment for school where I am trying to write a 2D string array into a text file. I have the array and know its working fine however every time I try to read the file into Streamwriter I get "System.ArgumentException: 'Illegal characters in path.'". I am relatively new to C# and I have no idea how to fix this.
This is my code. I just need to know how to write my 2D array into the text file without getting this error. Thanks, all and any help is much appreciated!
// This line under is where the error happens
using (var sw = new StreamWriter(Harvey_Norman.Properties.Resources.InventoryList))
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 3; j++)
{
sw.Write(InventoryArray[i, j] + " ");
}
sw.Write("\n");
}
sw.Flush();
sw.Close();
}
My guess is that Harvey_Norman.Properties.Resources.InventoryList is a resource in your project that is typed as a string-- and the value of that string is not a valid path for your operating system.
StreamWriter will either take a string, in which case it expects to open a file with the path of that string; or it will take a stream, and you can write to that stream. It looks like you are trying to do the former; but you need to check the value of that resource to see if it is a vaild path.
You're trying to construct a StreamWriter with an invalid file path.
Also, if you're just writing text out, you can use File.CreateText() to create a StreamWriter, for example:
var tempFilePath = Path.GetTempFileName();
using (var writer = File.CreateText(tempFilePath))
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 3; j++)
{
if (j > 0)
writer.WriteLine(" ");
writer.Write(InventoryArray[i, j]);
}
writer.WriteLine();
}
}
The using will automatically flush and close the file, and dispose the StreamWriter.

How can i write a datagrid to a textfile in WPF?

How can i write all my values in my datagrid not datagridview in a textfile i have the following code but it only saves the last values and not every value in the datagrid
my code
string file_name = "text.txt";
for (int i = 0; i < datagrid.Items.Count; i++)
{
//this is the class person
Person prsn = (Person)datagrid.Items[i];
File.WriteAllText(file_name, person.ToString());
}
How can i fix this?
File.WriteAllText writes the data in your file but when the loop increments, that data is overwritten. This goes on till the last loop and that's why you see only the last one in the file.
You need to hold the previous data and should write in file only when the loop is complete.
So do this
string file_name = "text.txt";
StringBuilder strBuilder = new StringBuilder():
for (int i = 0; i < datagrid.Items.Count; i++)
{
Person prsn = (Person)datagrid.Items[i];
strBuilder.Append(prsn.ToString());
}
File.WriteAllText(file_name, strBuilder.ToString());

trouble reading and writing to a file c#

I am currently trying to take a file of words that are not in alphabetical, re-order the words so that they are in alphabetical order (I am trying to use a non-built in sort method), and then write the newly ordered list into a new txt file(one that must be created). For example, lets say there is only five words in the txt file that are as follows "dog bat apple rabbit cat". I would want the program to resort these in alphabetical order, and then create a txt file that saves that order. As of right now, the program will iterate through the txt file, but will not save the re-ordered list into the new txt file. What is saved into the new file is this... "System.Collections.Generic.List`1[System.String]"
Truth be told, I am not very savvy with c# yet, so i apologize if my structuring or coding is not very well. The original file that is un-ordered is called "jumbled english FILTERED.ALL.txt", and the file I am trying to write to is called "english FILTERED.ALL.txt".
static void Main(string[] args)
{
// declaring integer for minimum.
int min = 0;
// declare the list for the original file
List<string> LinuxWords = new List<string>();
List<string> lexicalOrder = new List<string>();
// read the text from the file
string[] lines = System.IO.File.ReadAllLines("jumbled english FILTERED.ALL.txt");
string line = string.Empty;
// seperate each word into a string
//foreach (string line in lines)
//{
//add each word into the list.
//LinuxWords.Add(line);
//}
for (int i = 0; i < lines.Length - 1; i++)
{
for (int j = i + 1; j < lines.Length; j++)
{
if (lines[i].Length < lines[j].Length)
{
min = lines[i].Length;
}
else
{
min = lines[j].Length;
}
for (int k = 0; k < min; k++)
{
if (lines[i][k] > lines[j][k])
{
line = lines[i].ToString();
lines[i] = lines[j];
lines[j] = line;
break;
}
else if (lines[i][k] == lines[j][k])
{
continue;
}
else
{
break;
}
}
}
}
for (int i = 0; i < lines.Length; i++)
{
Console.WriteLine("The program is formatting the correct order");
lexicalOrder.Add(lines[i]);
}
//lexicalOrder.ForEach(Console.WriteLine);
//}
//LinuxWords.ForEach(Console.WriteLine);
File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "english FILTERED.ALL.txt",
lexicalOrder.ToString());
// write the ordered list back into another .txt file named "english FILTERED.ALL.txt"
// System.IO.File.WriteAllLines("english FILTERED.ALL.txt", lexicalOrder);
Console.WriteLine("Finished");
}
Assuming you mean that you don't get the list saved (if that's not the problem - please be more specific) - you need to change
lexicalOrder.ToString()
to something like
lexicalOrder.Aggregate((s1, s2) => s1 + " " + s2)

Replicate record in a DataTable based on value of a column using C#

I have a record in a dataTable as shown below.
1 Test 7Dec2014 15:40 one,two,three
Since the last column has 3 comma separated values, the resultant DataTable should like below with replicated records.
1 Test 7Dec2014 15:40 one
2 Test 7Dec2014 15:40 two
3 Test 7Dec2014 15:40 three
Please help me with an optimized way to achieve the above result.
The optimized way I found for the above problem is as below. If anybody has a better solution please let me know.
string[] strValues;
for (int i = 0; i < dtTable.Rows.Count; i++)
{
strValues= dtTable.Rows[i]["Column_Name"].ToString().Split(',');
if (strValues.Length > 1)
{
dtTable.Rows[i]["Column_Name"] = strValues[0];
for (int j = 1; j < strValues.Length; j++)
{
var TargetRow = dtTable.NewRow();
var OriginalRow = dtTable.Rows[i];
TargetRow.ItemArray = OriginalRow.ItemArray.Clone() as object[];
TargetRow["Column_Name"] = strValues[j];
dtTable.Rows.Add(TargetRow);
}
}
}

Categories

Resources