c# write an arraylist to a text file - c#

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");
}

Related

writing array values to file 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);

Whats the best way to programmatically read ildasm output

I'm trying to make ildasm output more like json or xml so that its somewhat easy to programmatically read it.
The way I intended to do it by reading the output line by line and then adding the classes and methods etc to lists and then modify and rewrite it as xml and then read it.
Question: Are there any smarter or simpler ways to read the output?
There is a way to get a list of classes and methods by reading IL Code.
The solution which i am telling might be a bit long but it will work.
IL is nothing but .exe or .dll . First try to convert this to C# or VB by using ILSpy . Download this tool and open your DLL into this. This tool can convert your IL Code into C# or VB.
After converting , save your converted code into a txt file.
Then read the text file and find the classes and methods inside it.
To read Method Names :
MatchCollection mc = Regex.Matches(str, #"(\s)([A-Z]+[a-z]+[A-Z]*)+\(");
To read Class Names :
Iterate through the file line by line and check whether the line has name "Class" . if it has the name then Split the values and store the value/text which comes after the name "Class" which is nothing but ClassName.
Complete Code :
static void Main(string[] args)
{
string line;
List<string> classLst = new List<string>();
List<string> methodLst = new List<string>();
System.IO.StreamReader file = new System.IO.StreamReader(#"C:\Users\******\Desktop\TreeView.txt");
string str = File.ReadAllText(#"C:\Users\*******\Desktop\TreeView.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains("class")&&!line.Contains("///"))
{
// for finding class names
int si = line.IndexOf("class");
string followstring = line.Substring(si);
if (!string.IsNullOrEmpty(followstring))
{
string[] spilts = followstring.Split(' ');
if(spilts.Length>1)
{
classLst.Add(spilts[1].ToString());
}
}
}
}
MatchCollection mc = Regex.Matches(str, #"(\s)([A-Z]+[a-z]+[A-Z]*)+\(");
foreach (Match m in mc)
{
methodLst.Add(m.ToString().Substring(1, m.ToString().Length - 2));
//Console.WriteLine(m.ToString().Substring(1, m.ToString().Length - 2));
}
file.Close();
Console.WriteLine("******** classes ***********");
foreach (var item in classLst)
{
Console.WriteLine(item);
}
Console.WriteLine("******** end of classes ***********");
Console.WriteLine("******** methods ***********");
foreach (var item in methodLst)
{
Console.WriteLine(item);
}
Console.WriteLine("******** end of methods ***********");
Console.ReadKey();
}
Here I am storing the class names and method names in a list. you can later store them in XML or JSON as you described above.
Ping us if you face any problem.

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.

txt file read/overwrite/append. Is this feasible? (Visual C#)

I'm writing a program for some data entry I have to periodically do. I have begun testing a few things that the program will have to do but i'm not sure about this part.
What i need this part to do is:
read a .txt file of data
take the first 12 characters from each line
take the first 12 characters from each line of the data that has been entered in a multi-line text box
compare the two lists line by line
if one of the 12 character blocks from the multi-line text box match one of the blocks in the .txt file then overwrite that entire line (only 17 characters in total)
if one of the 12 character blocks from the multi-line text box DO NOT match any of the blocks in the.txt file then append that entire line to the file
thats all it has to do.
i'll do an example:
TXT FILE:
G01:78:08:32 JG05
G08:80:93:10 JG02
G28:58:29:28 JG04
MULTI-LINE TEXT BOX:
G01:78:08:32 JG06
G28:58:29:28 JG03
G32:10:18:14 JG01
G32:18:50:78 JG07
RESULTING TXT FILE:
G01:78:08:32 JG06
G08:80:93:10 JG02
G28:58:29:28 JG03
G32:10:18:14 JG01
G32:18:50:78 JG07
as you can see lines 1 and 3 were overwriten, line 2 was left alone as it did not match any blocks in the text box, lines 4 and 5 were appended to the file.
thats all i want it to do.
How do i go about this?
Thanks in advance
Edit
The code i'm using is this:
private void WriteToFile()
{
// Read all lines from file into memory
System.IO.StreamReader objReader = new System.IO.StreamReader("Jumpgate List.JG");
List<String> fileTextList = new List<String>();
do
{
fileTextList.Add(objReader.ReadLine());
}
while (objReader.Peek() != -1);
objReader.Close();
// Read all lines from the Input textbox into memory
System.IO.StringReader objReaderi = new System.IO.StringReader(txtInput.Text);
List<String> inputTextList = new List<String>();
do
{
inputTextList.Add(objReaderi.ReadLine());
}
while (objReaderi.Peek() != -1);
objReaderi.Close();
for(int i=0;i<fileTextList.Count;i++)
{
for(int j=0;j<inputTextList.Count;j++)
//compare the first 12 characters of each string
if (String.Compare(fileTextList[i], 0, inputTextList[j], 0, 12) == 0) // strings are equal
{
//replace the fileTextList string with the inputTextList string
fileTextList[i] = inputTextList[j];
// now that you have matched you inputTextList line you remember not to append it at the end
inputTextList[j] = String.Empty; // or nothing
}
}
for(int i=0;i<inputTextList.Count;i++)
{
if (!string.IsNullOrEmpty(inputTextList[i])) fileTextList.Add(inputTextList[i]);
}
System.IO.StreamWriter objWriter = new System.IO.StreamWriter("Jumpgate List.JG");
// Overwrite the Jumpgate List.JG file using the updated fileTextList
objWriter.Write(fileTextList);
objWriter.Close();
}
However, when i open the txt file all i get is: System.Collections.Generic.List`1[System.String]
I'm not going to write the whole code for doing this but it would be something like this:
Disclaimer: I have not used a code editor to try the code, just wrote it here, hopefully you'll get the idea and fill in the missing pieces :)
1) get all the lines in the file in a list. Something like this
StreamReader rd = new StreamReader("sadasd");
List<String> llist = new List<String>();
do
{
llist.Add(rd.ReadLine());
} while (rd.Peek() != -1);
2) get all the lines in your multiline text box (the procedure should be similar to the one above): multiTextList
3) now that you can compare the content of the 2 lists iterating through them
for(int i=0;i<fileTextList.Count;i++)
{
for(int j=0;j<multiTextList.Count;j++)
//compare the first 12 characters of each string
if String.Compare(fileTextList[i], 0, multiTextList[j], 0, 12) == 0 // strings are equal
{
//replace the initial line with whatever you want
fileTextList[i] = //whatever
// now that you have matched you multiTextList line you remember not to append it at the end
multiTextList[j] = String.empty // or nothing
}
}
4) at the end you will have in fileTextList the initial rows, modified where necessary
In multiTextList you will have only the lines that were not matched so we add them to the initial file rows
for(int i=0;i<multiTextList.Count;i++)
{
if !string.isnullorempty(multitextlist[i]) fileTextList.add(multitextlist[i])
}
5) now in fileTextList you have all the rows you require so you can print them one by one in a file and you have your result
StringBuilder lSb = new StringBuilder();
for (int i = 0; i < fileTextList.Count; i++)
{
lSb.AppendLine(fileTextList[i]);
}
File.WriteAllText(#"C:/test2.txt",lSb.ToString());
In C:/test2.txt you should have the results.
Hope this helps!
// this variable maps the timestamps to complete lines
var dict = new Dictionary<string, string>();
// create the map of stamp => line for the original text file
string fileLine = file.ReadLine();
string fileStamp = fileLine.Substring(0, 12);
dict[fileStamp] = fileLine;
// now update the map with results from the text input. This will overwrite text
// strings that already exist in the file
foreach (string inputLine in textInputString.Split('\n'))
{
string inputStamp = inputLine.Substring(0, 12);
dict[inputStamp] = inputLine;
}
// write out the new file with the updated lines
foreach (string line in dict.Values)
{
outputFile.WriteLine(line);
}
if the file is large, loading the entire file into a dictionary to update a handful of lines from a textfield is probably excessive.
In pseudocode I would probably:
Create a list of booleans or other structure to track if a line was matched.
open the file in read/write mode.
For each line in file
{
for each unmatched line in text field
{
If stamps match
Update file
record that it was matched
}
}
for each unmatched line in text field
{
append to file
}
If the lines are fixed width, you can probably optimize by only reading the stamp rather than the whole line. If they match your file pointer is in the right spot to start writing, if not you move to the next line.

Categories