How to make seperate lines with c# (Textfile) - c#

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

Related

How to get data from text resource file and put in combobox

I have many files of data in txt files like this short example
123456
754124
956412
789654
They can have tens of lines in each file. Each file populates a separate combobox. From a static file in a folder I can make it work
string[] fname = {"fridge", "washer", "freezer", "dishwasher"};
for (int i = 0; i < fname.Length; i++)
{
string[] lineOfContents = File.ReadAllLines(#"d:\\temp\\" + fname[i] + ".txt");
ComboBox cmbobox = (ComboBox)this.Controls["cmbobx_" + fname[i]];
foreach (var line in lineOfContents)
{
string[] data = line.Split(new[] {Environment.NewLine}, StringSplitOptions.None);
cmbobox.Items.Add(data[0]);
}
cmbobox.SelectedIndex = 0;
}
but I need to do this when I read the data from embedded resources. I pulled the text files into the project.properties.resources so I have them inside the exe. I understand I will need to stream it out from resources but then I get lost in knowing how to convert the stream with all its newlines etc and format it to add it to the combobox.
I tried many things and the closest I think I have got is as follows although it tells me I have hold of nothing (NULL).
string[] fname = {"fridge", "washer", "freezer", "dishwasher"};
var assembly = Assembly.GetExecutingAssembly();
for (int i = 0; i < fname.Length; i++)
{
string lineOfContents;
string name = fname[i] + ".txt";
using (Stream resourceStream = assembly.GetManifestResourceStream(name))
{
if (resourceStream != null)
{
using (StreamReader reader = new StreamReader(resourceStream))
{
lineOfContents = reader.ReadToEnd();
}
}
}
ComboBox cmbobox = (ComboBox)this.Controls["cmbobx_" + fname[i]];
cmbobox.SelectedIndex = 0;
}
Any help in getting the stream into the combo box would be much appreciated.
Thanks for the link below, I did not get that when I searched so thanks and it helped. The working code before I tidy it up is:
string[] fname = {"fridge", "washer", "freezer", "dishwasher"};
for (int i = 0; i < fname.Length; i++)
{
string resource_data = Properties.Resources.ResourceManager.GetString(fname[i]);
string[] lineOfContents = resource_data.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
ComboBox cmbobox = (ComboBox)this.Controls["cmbobx_" + fname[i]];
foreach (var line in lineOfContents)
{
string[] data = line.Split(new[] {Environment.NewLine}, StringSplitOptions.None);
cmbobox.Items.Add(data[0]);
}
cmbobox.SelectedIndex = 0;
}
Thanks for the links, I did not get that when I searched so thanks and it helped. The working code before I tidy it up is:
string[] fname = {"fridge", "washer", "freezer", "dishwasher"};
for (int i = 0; i < fname.Length; i++)
{
string resource_data = Properties.Resources.ResourceManager.GetString(fname[i]);
string[] lineOfContents = resource_data.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
ComboBox cmbobox = (ComboBox)this.Controls["cmbobx_" + fname[i]];
foreach (var line in lineOfContents)
{
string[] data = line.Split(new[] {Environment.NewLine}, StringSplitOptions.None);
cmbobox.Items.Add(data[0]);
}
cmbobox.SelectedIndex = 0;
}

Reading, Manipulating, and Writing text files C#

I need to convert any flat delimited file into a pipe delimited format. I wrote this console app as a POC but the second file it tries to write will include the all of the text from the first file. Any suggestions?
string sourceDir = #"c:\temp\";
string targetDir = #"c:\dest\";
List<string> listLines = new List<string>();
string[] files = Directory.GetFiles(sourceDir);
foreach(string file in files)
{
using (StreamReader sr = new StreamReader(sourceDir + Path.GetFileName(file)))
{
do
{
listLines.Add(sr.ReadLine());
} while (!sr.EndOfStream);
for (int i = 0; i < listLines.Count; i++)
{
listLines[i] = listLines[i].Replace(',', '|');
listLines[i] = listLines[i].Replace('\t', '|');
}
}
using (StreamWriter sw = new StreamWriter(targetDir + Path.GetFileName(file)))
{
foreach (string line in listLines)
{
sw.WriteLine(line);
}
}
}
You need to either move the instantiation of listLines into the foreach, or re-initialize the list at the end of the loop.
string sourceDir = #"c:\temp\";
string targetDir = #"c:\dest\";
string[] files = Directory.GetFiles(sourceDir);
foreach(string file in files)
{
List<string> listLines = new List<string>();
using (StreamReader sr = new StreamReader(sourceDir + Path.GetFileName(file)))
{
do
{
listLines.Add(sr.ReadLine());
} while (!sr.EndOfStream);
for (int i = 0; i < listLines.Count; i++)
{
listLines[i] = listLines[i].Replace(',', '|');
listLines[i] = listLines[i].Replace('\t', '|');
}
}
using (StreamWriter sw = new StreamWriter(targetDir + Path.GetFileName(file)))
{
foreach (string line in listLines)
{
sw.WriteLine(line);
}
}
}
You're adding lines to listLines and never clearing the list after the foreach iteration.
by #Jonathan Carroll
Beside that, you can improve your code to this:
string sourceDir = #"c:\temp\";
string targetDir = #"c:\dest\";
List<string> listLines = new List<string>();
string[] files = Directory.GetFiles(sourceDir);
foreach (string file in files)
{
using (StreamReader sr = new StreamReader(sourceDir + Path.GetFileName(file)))
using (StreamWriter sw = new StreamWriter(targetDir + Path.GetFileName(file)))
{
do
{
var line = sr.ReadLine();
line = line.Replace(',', '|').Replace('\t', '|');
sw.WriteLine(line);
} while (!sr.EndOfStream);
}
}
I'd argue that the other answers are considerably clearer, but just thought I'd throw in a short alternative solution using LINQ and Regex:
foreach (var file in Directory.GetFiles(sourceDir).Select(x => Path.GetFileName(x)))
File.WriteAllText(targetDir + file, new Regex("[,\t]").Replace(File.ReadAllText(sourceDir + file), "|"));
The LINQ select query is used to transform the full paths into file names - this collection of file names is then iterated over.
Regex is used to match all ',' and '\t' characters that are read from the source file and replace them with the '|' character. This resulting string is then written to the target file.

how to read text files on android builds for Unity?

I've been having a lot of trouble trying to read text files stored in the StreamingAsset folder on my Android phone when I build the game as an .apk file.
I know that for Android you have to use a different path to access the files by using
"jar:file://" + Application.dataPath + "!/assets" + fileName;
and store it into the WWW class. I have tried many ways but nothing seems to work for me as I am totally lost right now. My code looks like this:
void Awake(){
string filePath = "jar:file://" + Application.dataPath + "!/assets" + fileName;
// Reads our text file and stores it in the array
string[][] Level = readFile (filePath);
}
// Reads our level text file and stores the information in a jagged array, then returns that array
string[][] readFile(string file){
WWW loadFile = new WWW (file);
while (!loadFile.isDone) {}
string text = System.IO.File.ReadAllText(loadFile.text);
string[] lines = Regex.Split(text, "\r\n");
int rows = lines.Length;
string[][] levelBase = new string[rows][];
for (int i = 0; i < lines.Length; i++) {
string[] stringsOfLine = Regex.Split(lines[i], " ");
levelBase[i] = stringsOfLine;
}
return levelBase;
}
You can use streamreader for this:
List<string> lines = new List<string>();
using (StreamReader reader = new StreamReader("file.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
lines.Add(line);
}
}
The line string text = System.IO.File.ReadAllText(loadFile.text); is wrong:
loadFile.text already contains the contents of file you are trying to open with System.IO.File.ReadAllText
Also you can't use the System.IO.File.ReadAllText method to access file from StreamingAssets on Android.

Split file line by line into an array

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

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

Categories