writing array values to file C# - c#

I am trying to write the values of my array to a text file, but my output isn't cooperating.
my code
using (StreamWriter outputFile = new StreamWriter(#"C:\Users\fakeuser\Desktop\C#\New Text Document.txt"))
{
string[] values = { "Test", "People", "Owls", "Bully"};
foreach (string line in values)
outputFile.WriteLine(values);
this is the output I get
What am I missing here?

The problem is you're writing the array instead of the line you're iterating over. Try this instead:
outputFile.WriteLine(line);
Alternatively, you could replace the whole loop with this:
File.WriteAllLines("that long path", values);

You have a typo in your code. Try this:
outputFile.WriteLine(line);

Related

C#: How to make Stream Reader to Int

I'm reading from a file with numbers and then when I try to convert it to an Int I get this error, System.FormatException: 'Input string was not in a correct format.' Reading the file works and I've tested all of that, it just seems to get stuck on this no matter what I try. This is what I've done so far:
StreamReader share_1 = new StreamReader("Share_1_256.txt");
string data_1 = share_1.ReadToEnd();
int intData1 = Int16.Parse(data_1);
And then if parse is in it doesn't print anything.
As we can see in your post, your input file contains not one number but several. So what you will need is to iterate through all lines of your file, then try the parsing for each lines of your string.
EDIT: The old code was using a external library. For raw C#, try:
using (StringReader reader = new StringReader(input))
{
string line;
while ((line = reader.ReadLine()) != null)
{
// Do something with the line
}
}
In addition, I encourage you to always parse string to number using the TryParse method, not the Parse one.
You can find some details and different implementations for that common problem in C#: C#: Looping through lines of multiline string
parser every single line
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
int intData1 = Int16.Parse(line);
}
You can simplify the code and get rid of StreamReader with a help of File class and Linq:
// Turn text file into IEnumerable<int>:
var data = File
.ReadLines("Share_1_256.txt")
.Select(line => int.Parse(line));
//TODO: add .OrderBy(item => item); if you want to sort items
// Loop over all numbers within file: 15, 1, 48, ..., 32
foreach (int item in data) {
//TODO: Put relevant code here, e.g. Console.WriteLine(item);
}

Read a CSV file and writer into a file without " " using C#

I am trying to read a CSV file and stored all the values in the single list.CSV file contains credentials as uid(userid) and pass(password) and separated by','I have successfully read all the lines and write it in the file.but when it writes in the file, it write the value in between " "(double quotes) like as("abcdefgh3 12345678")what i want actually to remove this "" double quotes sign when i write it in to the files.i am pasting my code here:
static void Main(string[] args)
{
var reader = new StreamReader(File.OpenRead(#"C:\Desktop\userid1.csv"));
List<string> listA = new List<string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
listA.Add(values[0]);
listA.Add(values[1]);
}
foreach (string a in listA)
{
TextWriter tr = new StreamWriter(#"E:\newfiless",true);
tr.Write(a);
tr.Write(tr.NewLine);
tr.Close();
}
}
and the resulted output is like this:
"uid
pass"
"Martin123
123456789"
"Damian
91644"
but i want in this form:
uid
pass
Martin123
123456789
Damian
91644
Thanking you all in advance.
The original file clearly has quotes, which makes it a CSV file with only one colum and in that column there are two values. Not usual, but it happens.
To actually remove quotes you can use Trim, TrimEnd or TrimStart.
You can remove the quotes while reading, or while writing, in this case it doesn't really matter.
var line = reader.ReadLine().Trim('"');
This will remove the quotes while reading. Note that this assumes the CSV is of this "broken" variant.
tr.WriteLine(a.Trim('"'));
This will handle it on write. This will work even if the file is "correct" CSV having two columns and values in quotes.
Note that you can use WriteLine to add the newline, no need for two Write calls.
Also as others have commented, don't create a TextWriter in the loop for every value, create it once.
using (TextWriter tr = new StreamWriter(#"E:\newfiless"))
{
foreach (string a in listA)
{
tr.WriteLine(a.Trim('"'));
}
}
The using will take care of closing the file and other possible resources even if there is an exception.
I assume that all you need to read the input file, strip out all starting/ending quotation marks, then split by comma and write it all to another file. You can actually accomplish it in a one-liner using SelectMany, which will produce a "flat" collection:
File.WriteAllLines(
#"c:\temp\output.txt",
File
.ReadAllLines(#"c:\temp\input.csv")
.SelectMany(line => line.Trim('"').Split(','))
);
It's not quite clear from your example where quotation marks are located in the file. For a typical .CSV file some comma-separated field might be wrapped in quotation marks to allow commas to be a part of the content. If it's the case, then parsing will be more complex.
You can use
tr.Write(a.Substring(1, line.Length - 2));
Edited
Please use Trim
tr.Write(a.TrimEnd('"').TrimStart('"'));

How do I separate each line of a .csv file into a string list>

I am new to c# and am attempting to read in a .csv file and put each line of text in to a separate list item so I can sort it later.
the .csv file is organised like so:
1;"final60";"United Kingdom";"2013-12-06 15:48:16";
2;"donnyr8";"Netherlands";"2013-12-06 15:54:32";
etc
This is my first attempt that doesn't work.It shows no errors in Visual studios 2010 but when I run the console program it displays the following Exception instead of the list.
Exception of type 'System.OutOFMemoryException' was thrown. Which is bizarre because the .csv file only contains a small list.
try
{
// load csv file
using (StreamReader file = new StreamReader("file.csv"))
{
string line = file.ReadLine();
List<string> fileList = new List<string>();
// Do something with the lines from the file until the end of
// the file is reached.
while (line != null)
{
fileList.Add(line);
}
foreach (string fileListLine in fileList)
{
Console.WriteLine(fileListLine);
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
So am I approaching this the correct way?
If the file you are loading isn't really big then you can use File.ReadAllLines:
List<string> list = File.ReadAllLines("file.csv").ToList();
As Servy pointed out in comment it would be better to use File.ReadLines method.
File.ReadLines - MSDN
The ReadLines and ReadAllLines methods differ as follows: When you use
ReadLines, you can start enumerating the collection of strings before
the whole collection is returned; when you use ReadAllLines, you must
wait for the whole array of strings be returned before you can access
the array. Therefore, when you are working with very large files,
ReadLines can be more efficient.
If you need a List<string> then you can do:
List<string> list = File.ReadLines("file.csv").ToList();
You are not updating the line variable so the line will be always different from null infinite loop which cause OutOfMemoryException
try
{
// load csv file
using (StreamReader file = new StreamReader("file.csv"))
{
string line = file.ReadLine();
List<string> fileList = new List<string>();
// Do something with the lines from the file until the end of
// the file is reached.
while (line != null)
{
fileList.Add(line);
line = file.ReadLine();
}
foreach (string fileListLine in fileList)
{
Console.WriteLine(fileListLine);
}
}
}
but the correct approaches will be
List<string> list = File.ReadLines("file.csv").ToList();
which is better than File.ReadAllLines for the following reason
From MSDN:
When you use ReadLines, you can start enumerating the collection of strings before the whole collection is returned;
You should use File.ReadAllLines() and then parse the strings in the array.
For extremely large files this might not be feasible and you'll have to stream the single lines in and process them one by one.
But this is something you can only decide AFTER you have seen this quick approach failing miserably. Until then, stick to the quick and dirty.

c# write an arraylist to a text file

I need to write my array list into a text file and so far have come up with this code.
Now im confused as to how to write the 'line' to my text file using the textwriter?
One procedure loads the list out of a txt file below.
public void LoadArrayList()
{
TextReader tr;
tr = File.OpenText("C:\\Users\\Mirro\\Documents\\Visual Studio 2010\\Projects\\Assessment2\\Assessment2\\act\\actors.txt");
string line = tr.ReadToEnd();
Console.WriteLine(line);
if (line != null)
{
ActorArrayList.Add(line);
}
else
tr.Close();
}
Then i have one that will populate the combo box in my form.
public void PopulateActors()
{
cboActor.Items.Clear();
foreach (string line in ActorArrayList)
{
cboActor.Items.AddRange(File.ReadAllLines("C:\\Users\\Mirro\\Documents\\Visual Studio 2010\\Projects\\Assessment2\\Assessment2\\act\\actors.txt"));
}
}
and this procedure i need it to write my whole array "ActoryArrayList" into the text file.
public void WriteArrayList()
{
}
Im sorry for being confusing originally.
Try with following code
// Example #1: Write an array of strings to a file.
// Create a string array that consists of three lines.
string[] lines = { "First line", "Second line", "Third line" };
// WriteAllLines creates a file, writes a collection of strings to the file,
// and then closes the file.
System.IO.File.WriteAllLines(#"C:\Users\Mirro\Documents\Visual Studio 2010\Projects\Assessment2\Assessment2\act\actors.txt", lines);
OUTPUT :
// First line
// Second line
// Third line
The best way is #Leez's way, but You also may use TextWriter and foreach operator to make this:
//your array
string[] yourArray = { "fisrt", "second", "third" };
string text = "C:\\Users\\Mirro\\Documents\\Visual Studio 2010\\Projects\\Assessment2\\Assessment2\\act\\actors.txt";
using (TextWriter writer = File.CreateText(text))
{
foreach (string i in yourArray)
{
writer.WriteLine(i);
}
}
System.IO.File.WriteAllText("FILE_PATH", line);
BTW, where is the ArrayList in your code? Also, consider using System.IO.File.ReadAllText("FILE_PATH") for everyday file reading.
If you were to actually write an ArrayList to a disk file, that would require you to first serialize the contents of the ArrayList to maybe XML or binary etc. Then you can use the above methods to write that serialized representation to a file. Also note that serializing collections involves a concept called deep and shallow copying. This question may help you better understand the concept.
File.WriteAllLines(filePath, ActorArrayList.ToArray());
WriteAllLines outputs two end of line characters (carriage return and line feed - \r\n). If you don't want two end of line characters at the end of each line (\r\n), you can output only one character (\n) by using StreamWriter.
using (StreamWriter sw = new StreamWriter(#"C:\mypath\file.txt"))
{
foreach (string s in linesArray)
sw.Write(s + "\n");
}

C# StreamReader save to Array with separator

I´ve got a text file with tabulator separated data. What I need in my C# application is that I read one line from the text file and save them to an array, separate them at the each \t. Then I do the same thing with the next row.
My code:
StreamReader sr = new StreamReader(dlg.FileName);
string s = sr.ReadLine();
Now, I already tried to write the line into an array but that doesn´t work. Does anyone one how to manage this?
Use the Split method to create an Array of the line
string[] parts = s.Split('\t');
See Documentation on Split() here
foreach (string line in System.IO.File.ReadAllLines(dlg.FileName))
{
var myArray = line.Split('\t');
}
s.Split('\t') will split your string by the tabulator character, and create a string[] with appropriate length.
Ammending your example code:
StreamReader sr = new StreamReader(dlg.FileName);
string s = sr.ReadLine();
var items = s.Split('\t');
In the end, items contains an array of strings that represent the characters between the tabs. The tabs are not included in the array. The array may contain empty elements (for the case of two consecutive tabs).
Use the String.Split() method: http://msdn.microsoft.com/en-us/library/b873y76a.aspx
StreamReader reader = new StreamReader("input.txt");
string[] content = reader.ReadToEnd().Replace("\n","").Split('\t');
if you want to keep New Line's than
string[] content = reader.ReadToEnd().Split('\t');
In the example below, items will be a String[] containing each line of text's values. It will be overwritten with each iteration so you'll want to do something with it inside the loop. Save it to a larger collection, write it to a file, etc...
StreamReader sr = new StreamReader(dlg.FileName);
while (sr.Peek() >= 0) {
var line = sr.ReadLine();
var items = line.Split(new Char[] { '\t' });
}
If the file contains only one line, then use:
string[] myArray = s.Split('\t');

Categories