This doesnt work:
string fileContent = Resource.text;
StreamReader read = File.OpenText(fileContent);
string line;
char[] splitChar = "|".ToCharArray();
while ((line = read.ReadLine()) != null)
{
string[] split = line.Split(splitChar);
string name = split[0];
string lastname = split[1];
}
read.Dispose();
How do you open a resource file to get its contents?
Try like this:
string fileContent = Resource.text;
using (var reader = new StringReader(fileContent))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string[] split = line.Split('|');
string name = split[0];
string lastname = split[1];
}
}
I think the variable fileContent already has all the contents you need.
to read resources, you need a special Stream named "ResourceReader", you can use it like this :
string fileContent = "<your resource file>";
using (ResourceReader reader = new ResourceReader(fileContent))
{
foreach (IDictionaryEnumerator dict in reader)
{
string key = dict.Key as string;
object val = dict.Value;
}
}
Related
File consist of 2 line of text.
need to parse the file so that each line of text is assigned to a string. my string variables are "PhoneNumber" and "Location" and the incoming file is stored in string "line".
using (var sr = new StreamReader(incoming))
{
while ((line = sr.ReadLine()) != null)
{
PhoneNumber = ??
Location = ??
}
}
Maybe something like this?
using System.IO;
string Phonenumber = "";
string Location = "";
string[] filecontent = File.ReadAllLines("Filepath");
if (filecontent.Length > 0)
Phonenumber = filecontent[0];
if (filecontent.Length > 1)
Location = filecontent[1];
Edit:
Option 2 using StreamReader:
string Phonenumber = "";
string Location = "";
int LineCount = 0;
using (var sr = new StreamReader(#"Path"))
{
var linecontent = "";
while ((linecontent = sr.ReadLine()) != null)
{
if (LineCount == 0)
Phonenumber = linecontent;
if (LineCount == 1)
Location = linecontent;
LineCount++;
}
}
Option 3 also using StreamReader:
using (var sr = new StreamReader(#"Path"))
{
string Phonenumber = "";
string Location = "";
string[] filecontent = sr.ReadToEnd().Split("\n"); //Read text from file and split it into single lines
if (filecontent.Length > 0)
Phonenumber = filecontent[0];
if (filecontent.Length > 1)
Location = filecontent[1];
}
I am trying to use this code to create a list. It is failing at the NewCrime Convert step. Not sure how to use the stream reader. It is my first time and I usually use SQL so I have attempted to do the same thing I would do reading SQL here.
List MasterCrimeList;
public List<Crime.Crime> GetList()
{
MasterCrimeList = new List<Crime.Crime>();
try
{
string path = #"F:\\FanshaweCollegeClasses\\Winter2020\\CLAYS_FINAL_EXAM_2020\\VANHEESfinalEXAM\\SacramentocrimeJanuary2006.csv";
if (File.Exists(path))
{
// Open the file to read from.
using (StreamReader sr = File.OpenText(path))
{
string s;
while ((s = sr.ReadLine()) != null)
{
Crime.Crime NewCrime = new Crime.Crime(Convert.ToString(s[0]),//CrimeDateTime
Convert.ToString(s[1]),//CrimeAddress
Convert.ToInt32(Convert.ToString(s[2])),//CrimeDistrict
Convert.ToString(s[3]),//CrimeBeat
Convert.ToInt32(Convert.ToString(s[4])),//CrimeGrid
Convert.ToString(s[5]),//CrimeDescription
Convert.ToInt32(Convert.ToString(s[6])),//ncicCode
decimal.Parse(Convert.ToString(s[7])),//Latitude DECIMAL
decimal.Parse(Convert.ToString(s[8])));//Longitude DECIMAL
MasterCrimeList.Add(NewCrime);
}
}
}
}
When doing s[0] you're reading only one char of the whole line. What you should do is to split each line based on how the values are stored using Split(), and then you can access each value as an array. If it's a csv file:
string s;
while ((s = sr.ReadLine()) != null)
{
string[] lineValues = s.Split(new char[]{','});
string firstValue = lineValues[0];
string secondValue = lineValues[1];
...
}
Trying to override a single record of the following CSV:
PRODUCT,RECORD,ACCOUNT
100,200,300
using this code:
public static void UpdateCSV(string filePath, string stringToReplace, string updatedString)
{
string path = filePath;
List<string> lines = new List<string>();
if (File.Exists(path))
{
using (StreamReader reader = new StreamReader(path))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (line.Contains(","))
{
string[] split = line.Split(',');
if (split[1].Contains(stringToReplace))
{
split[1] = updatedString;
line = string.Join(",", split);
}
}
lines.Add(line);
}
}
using (StreamWriter writer = new StreamWriter(path, false))
{
foreach (string line in lines)
writer.WriteLine(line);
}
}
}
But invoking the following does not make a difference ('PRODUCT' does not change to 'MYPRODUCT'):
UpdateCSV(#"C:\Test.csv", "PRODUCT", "MYPRODUCT");
What's wrong here?
I am currently using the below code to compare two csv files with each other. This code gives an output with all the rows that are not the same. But when a row is missing everything after that row is not the same. How can I fix this? Thanks in advance.
List<string> lines = new List<string>();
List<string> lines2 = new List<string>();
try
{
StreamReader reader = new StreamReader(System.IO.File.OpenRead(file1));
StreamReader read = new StreamReader(System.IO.File.OpenRead(file2));
List<string> differences = new List<string>();
string line;
string line2;
int i = 0;
while ((line = reader.ReadLine()) != null && (line2 = read.ReadLine()) != null)
{
string[] split = line.Split(Convert.ToChar("\t"));
string[] split2 = line2.Split(Convert.ToChar("\t"));
if (split[i] != split2[i])
{
differences.Add("this row is not the same:, " + line);
}
else
{
}
i++;
}
System.IO.File.WriteAllLines(differencesFile, differences);
reader.Dispose();
read.Dispose();
}
catch
{
}
After help from a friend I made it work with this code:
List<string> file1 = new List<string>();
List<string> output = new List<string>();
string differencesFile = path;
File.WriteAllText(differencesFile, "");
try
{
StreamReader readFile1 = new StreamReader(System.IO.File.OpenRead(pathfile1));
string lineFile1;
while ((lineFile1 = readFile1.ReadLine()) != null)
{
bool match = false;
string[] colums = lineFile1.Split('\t');
StreamReader readFile2 = new StreamReader(System.IO.File.OpenRead(pathfile2));
string line2;
while ((line2 = readFile2.ReadLine()) != null)
{
string[] columsFile2 = line2.Split('\t');
if (colums[0] == columsFile2[0])
{
match = true;
}
}
if (!match)
{
output.Add(colums[0] + "; doesnt exist in pathfile2");
}
}
System.IO.File.WriteAllLines(differencesFile, output);
}
catch { }
So, I know my headline is a bit confusing, I will explain.
My code looks like this:
string filename = "C:\\C#\\maplist.txt"; // please put the text file path.
string filename2 = "C:\\C#\\zemaplist.txt";
string map;
StreamReader sr = new StreamReader(filename);
StreamWriter sw = new StreamWriter(filename2);
List<string> maps = new List<string> { };
while ((map = sr.ReadLine()) != null)
{
maps.Add(map);
}
sr.Close();
for (int i = 0; i < maps.Count; i++)
{
Console.WriteLine(maps[i]);
sw.WriteLine(maps[i]);
}
sw.Close();
and what i need to do is when the code read a new line, in my line there is
"Hey,Hey"
I want to split the , from each other so I can take both of them as other parameters, so that the first Hey will be added to maps and the other hey will be maps2,
How can I do that?
You can use Split() function to Split the given String based on delimiter.
Try This:
while ((map = sr.ReadLine()) != null)
{
maps.Add(map.Split(',')[0].Trim());
maps2.Add(map.Split(',')[1].Trim());
}
Simple Code:
using System.IO;
string filename = "C:\\C#\\maplist.txt"; // please put the text file path.
string filename2 = "C:\\C#\\zemaplist.txt";
string map;
StreamWriter sw = new StreamWriter(filename2);
List<string> maps = new List<string> { };
List<string> maps2 = new List<string> { };
String [] allLines = File.ReadAllLines(filename);
foreach(String line in allLines)
{
maps.Add(line.Split(',')[0].Trim());
maps2.Add(line.Split(',')[1].Trim());
}
for (int i = 0; i < maps.Count; i++)
{
Console.WriteLine(maps[i]);
sw.WriteLine(maps[i]);
}
sw.Close();
Solution 2:
String mapItem1="";
String mapItem2="";
if(maps.Count == maps2.Count)
{
for(int i=0;i<maps.Count;i++)
{
mapItem1=maps[i];
mapItem2=maps2[i];
}
}
while ((map = sr.ReadLine()) != null)
{
string[] split = map.Split(',');
//First Hey would be split[0], second Hey would be split[1]
maps.Add(split[0].Trim());
maps2.Add(split[1].Trim());
}
The Split method should help you out with that.
If you want to trim leading whitespace characters, you can use the .Trim() method on a string.
Use Split().
string heys = "Hey,Hey";
string[] splitArray = heys.Split(',');
Then you have:
splitArray[0] = "Hey";
splitArray[1] = "Hey";
Why even bother reading line by line? Read the entire file, replace the new line chars for a "," (to prevent last and first elements from different lines to be treated as one), and loop through a clean string.
string fileContent = Regex.Replace(File.ReadAllText("test.txt"), #"\r", ",");
List<string> mapList = new List<string>();
foreach (string map in Regex.Split(fileContent.Replace(#"\s+", ""), ","))
{
mapList.Add(map.Trim());
}