Split file line by line into an array - c#

I want to have an array based on the lines in the file, but at the moment its a fixed sized array:
string[] converList = new string[6]; // Array containing TXT lines
Reading the file:
void ReadConver()
{
string line;
int i = 0;
System.IO.StreamReader file =
new System.IO.StreamReader("C:\\Users\\Kennyist\\Documents\\Visual Studio 2010\\Projects\\soft140as3\\convert.txt");
while ((line = file.ReadLine()) != null)
{
converList[i] = line;
i++;
}
}
How would I do this?

You could create a list then use ToArray to make it into an array:
var cList = File.ReadAllLines("C:\\Users\\Kennyist\\Documents\\Visual Studio 2010\\Projects\\soft140as3\\convert.txt").ToList();
string[] converlist = clist.ToArray();
Also, use (#'C:\Kennyist...') instead of the double backslashes

Instead of doing things the hard way, you can just use:
var arrTextLines = File.ReadAllLines(#"C:\Users\Kennyist\Documents\Visual Studio 2010\Projects\soft140as3\convert.txt");
arrTextLines will be an object with the type string[].

Edited answer:
string[] converList;
System.IO.StreamReader file =
new System.IO.StreamReader("C:\\Users\\Kennyist\\Documents\\Visual Studio 2010\\Projects\\soft140as3\\convert.txt");
converList = new string[] { file.ReadToEnd() };
Thanks #Cole

Related

Streamreader Line with commas into a dictionary

I have a text file that contains lines and each line is seperated with a comma.
I want to put the data on the dictionary that will get the key and value based on the text file's values that are seperated in comma on each line.
txt row example:
{
key, value
}
I first get the data in a loop. If it was simply a string then i would know how to do it but the fact that i am firstly reading it from a streamReader it gives me problems. In a normal list it also worked but in this method it just doesn't work on the dictionary. Here is the code:
StreamReader sr = new StreamReader("Text.txt");
string line;
int i = 0;
while ((line = sr.ReadLine()) != null)
{
string[] arr = line.Split(',');
dict.Add(arr[i], arr[i + 1]);
i= i+2;
}
I got stuck in the dict.Add . I know it shouldn't be the arr as i wrote.
Thanks for any help!
Your question is almost impossibly unclear. But from what I could decipher, you either need another while loop:
StreamReader sr = new StreamReader("Text.txt");
string line;
while ((line = sr.ReadLine()) != null)
{
string[] arr = line.Split(',');
int i = 0;
while (i < arr.Length)
{
dict.Add(arr[i], arr[i + 1]);
i+=2;
}
}
Or your need forget about your i variable entirely:
StreamReader sr = new StreamReader("Text.txt");
string line;
while ((line = sr.ReadLine()) != null)
{
string[] arr = line.Split(',');
dict.Add(arr[0], arr[1]);
}
One of those should be right. Which one depends on whether you have multiple sets of values per line or not. The text of your question makes this impossible to guess.
And fwiw, string.Split() is usually a really horrible way to handle comma-separated data.

Why isn't there newline on this file write?

I have written some code to compare 2 files and write their common lines to a 3rd file. For some reason though the 3rd file which contains the common lines has ALL the common lines written to it on 1 line. This should really be 1 new line per common line..I have even tried adding Console.WriteLine('\n'); to add a new line to separate the common lines but this isn't helping. Any ideas as to what is wrong?
//This program will read files and compares to see if they have a line in common
//if there is a line in common then it writes than common line to a new file
static void Main(string[] args)
{
int counter = 0;
string line;
string sline;
string[] words;
string[] samacc = new string[280];
//first file to compare
System.IO.StreamReader sfile =
new System.IO.StreamReader("C:\\Desktop\\autoit\\New folder\\userlist.txt");
while ((sline = sfile.ReadLine()) != null)
{
samacc[counter] = sline;
Console.WriteLine();
counter++;
}
sfile.Close();
//file to write common lines to.
System.IO.StreamWriter wfile = new System.IO.StreamWriter("C:\\Desktop\\autoit\\New folder\\KenUserList.txt");
counter = 0;
//second file to compare
System.IO.StreamReader file =
new System.IO.StreamReader("C:\\Desktop\\autoit\\New folder\\AllUserHomeDirectories.txt");
while ((line = file.ReadLine()) != null)
{
words = line.Split('\t');
foreach (string i in samacc)
{
if (words[0] == i)
{
foreach (string x in words)
{
wfile.Write(x);
wfile.Write('\t');
}
Console.WriteLine('\n');
}
}
}
file.Close();
wfile.Close();
// Suspend the screen.
Console.ReadLine();
}
Change Console.WriteLine('\n'); to wfile.WriteLine('\n');
You can do this in a much better way:
var file1 = File.ReadLines(#"path1");
var file2 = File.ReadLines(#"path2");
var common = file1.Intersect(file2); //returns all lines common to both files
File.WriteAllLines("path3", common);

Why is this code not replacing data in a text file?

I'm working on a small app which should read a file (ANSI 835) and replace data at certain positions with generic data. Basically I'm trying to scrub a person's first and last name from the file.
The line I'm searching for that contains the name looks like this:
NM1*QC*1*Doe*John*R***MI*010088307 01~
My code looks like this:
string[] input_file = (string[])(e.Data.GetData(DataFormats.FileDrop));
string output_file = #"c:\scrubbed.txt";
foreach (string file in input_file)
{
string[] lines = File.ReadAllLines(file);
foreach (string line in lines)
{
if (line.StartsWith("NM1*QC"))
{
line.Split('*')[1] = "Lastname";
line.Split('*')[2] = "Firstname";
}
}
File.WriteAllLines(output_file, lines);
}
The File.WriteAllLines works, but the data isn't being changed. I'm trying to get any line that starts with NM1*QC to look like this:
NM1*QC*1*Lastname*Firstname*R***MI*010088307 01~
There are many lines in the file that start with NM1*QC. What's the proper way to 'find and replace' and then create a new file in this situation?
As always, thanks for your time!
The calls to String.Split return variables that you neither capture, nor use, they do not change the underlying string. So your code equates to this:
if (line.StartsWith("NM1*QC"))
{
string[] split1 = line.Split('*')[1] = "Lastname";
string[] split2 = line.Split('*')[2] = "Firstname";
}
You would need to take the results of split1 and split2 and use those to recreate your string. Here is how I would re-write your code:
string[] input_file = (string[])(e.Data.GetData(DataFormats.FileDrop));
string output_file = #"c:\scrubbed.txt";
foreach (string file in input_file)
{
string[] lines = File.ReadAllLines(file);
for (int i=0; i < lines.length; i++)
{
string line = lines[i];
if (line.StartsWith("NM1*QC"))
{
string[] values = line.Split('*');
values[1] = "Lastname";
values[2] = "Firstname";
lines[i] = String.Join("*", values);
}
}
File.WriteAllLines(output_file, lines);
}
Notice I am recombining the individual values using the String.Join method, and inserting the new string back into the array of lines. That will then get written out as you expect.
Here you are creating a temporary array:
line.Split('*')
And you are changing its contents:
line.Split('*')[1] = "Lastname";
After the line has been executed the reference to this temporary array is lost and along with it go your changes.
In order to persist the changes you need to write directly to lines:
for (var i = 0; i < lines.Length; ++i)
{
var line = lines[i];
if (!line.StartsWith("NM1*QC"))
{
continue;
}
var parts = line.Split('*');
parts[3] = "Lastname";
parts[4] = "Firstname";
lines[i] = string.Join("*", parts);
}

How to make seperate lines with c# (Textfile)

I'm making this application for fun but i have a problem
I want this string/file to be read in seperate lines.
this the file(not the whole file):
1ChampSelectPack.Ahri.mp31ChampSelectPack.Akali.mp31ChampSelectPack.Alistar.mp31ChampSelectPack.Amumu.mp31ChampSelectPack.Anivia.mp31ChampSelectPack.Annie.mp31ChampSelectPack.Ashe.mp31ChampSelectPack.Blitzcrank.mp31ChampSelectPack.Brand.mp31ChampSelectPack.Caitlyn.mp3
and this is what i got so far:
List<SoundPath> paths = new List<SoundPath>();
StreamReader reader = File.OpenText("C:/Users/Esat/Documents/Visual Studio 2010/Projects/WikiLoL/WikiLoL/lolSoundBoard/1ChampSelectPack/files.txt");
while (!reader.EndOfStream)
{
SoundPath path = new SoundPath();
path.Path = reader.ReadLine();
paths.Add(path);
}
reader.Close();
return paths;
Not sure if that is what you want:
"YourString".Split(new string[] {"mp3"}, StringSplitOptions.None)
You would have to append the "mp3" on each line afterwards.
You can do it using splitting on .mp3 and adding .mp3 in each element of resultant array.
string text = File.ReadAllText("C:/Users/Esat/Documents/Visual Studio 2010/Projects/WikiLoL/WikiLoL/lolSoundBoard/1ChampSelectPack/files.txt");
string[] lines = text.Split(new string[] { ".mp3" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < lines.Length; i++)
lines[i] = lines[i] + ".mp3";

C#: Searching for a keyword in a txt file

I have a problem reading a comma-delimited TXT file. This is what I am trying to do. I'm searching a text file for a keyword and then, when I've found the line containing that keyword, getting the whole line of comma-delimited keywords into a string array. How can I do this?
Thanks
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
String line;
String[] array;
while((line = file.ReadLine()) != null)
{
if (line.Contains("myString"))
{
array = line.Split(',');
}
}
file.Close();
In the if part yo can save your comma separated strings to an array
Basically, you're going to want to read the file line by line and check each of those lines for your string. When you find it, you'll take that line and split it into an array.
string temp = "";
string[] list;
IO.FileStream file = new IO.FileStream("MyFile.txt", IO.FileMode.Open);
IO.StreamReader reader = new IO.StreamReader(file);
While (!reader.EndOfStream)
{
temp = reader.ReadLine();
if (temp.Contains("myString")
{
list = temp.split(",");
break;
}
}
reader.close();

Categories