StreamReader from .csv - "foreign" chars and blank values showing up as '?' - c#

I'm having two problems with reading my .csv file with streamreader. What I'm trying to do is get the values, put them into variables which I'll be using later on, inputting the values into a browser via Selenium.
Here's my code (the Console.Writeline at the end is just for debugging):
string[] read;
char[] seperators = { ';' };
StreamReader sr = new StreamReader(#"C:\filename.csv", Encoding.Default, true);
string data = sr.ReadLine();
while((data = sr.ReadLine()) != null)
{
read = data.Split(seperators);
string cpr = read[0];
string ydelsesKode = read[1];
string startDato = read[3];
string stopDato = read[4];
string leverandoer = read[5];
string leverandoerAdd = read[6];
Console.WriteLine(cpr + " " + ydelsesKode + " " + startDato + " " + stopDato + " " + leverandoer + " " + leverandoerAdd);
}
The code in and of itself works just fine - but I have two problems:
The file has values in Danish, which means I get åøæ, but they're showing up as '?' in console. In notepad those characters look fine.
Blank values also show up as '?'. Is there any way I can turn them into a blank space so Selenium won't get "confused"?
Sample output:
1372 1.1 01-10-2013 01-10-2013 Bakkev?nget - dagcenter ?
Bakkev?nget should be Bakkevænget and the final '?' should be blank (or rather, a bank space).

"Fixed" it by going with tab delimited unicode .txt file instead of .csv. For some reason my version of excel doesn't have the option to save in unicode .csv...
Don't quite understand the problem of "rolling my own" parser, but maybe someday someone will take the time to explain it to me better. Still new-ish at this c# stuff...

Related

C# move path includes invalid characters

I've been trying to do a renamer program in c# for 2 different paths and I keep getting error "Path includes invalid characters" I have no clue how to fix it, I've tried adding # and deleting \ and keeping only one . But still didn't figure out how to fix it. Would love any help.
This is what gives me an error:
if (French.Checked)
{
directoryfile = #"C:\Users\" + curruser + #"\Appdata\Local\fo4renamer\directory.txt";
label1.Text = directoryfile;
readpath = File.ReadAllText(directoryfile);
string shouldwork = readpath + "data";
string french = shouldwork + "\\french";
string german = shouldwork + "\\german";
string tmp = shouldwork + "tmp.txt";
label1.Text = french;
string path2 = #"C:\Users\duchacekda\Desktop\e\Renamer\Renamer\bin\Debug\tmp.txt";
string filename = #"C:\Users\duchacekda\Desktop\e\Renamer\Renamer\bin\Debug\french.txt";
File.Move(french, german);
}
Here is the whole code:
https://pastebin.com/0i7fzh24
Edit: this is the string for curruser
string curruser = System.Environment.UserName;
The exception was given by this line
File.Move(french, german);
File.ReadAllText Method (String) : Opens a text file, reads all lines of the file, and then closes the file.
So in your scenario :
string french = (Content of directory.txt) + "data" + "\\french";
It depends on content of directory.txt
a) If content = directory path(c:\foo) there is no problem
b) if content = "dummy text *** dummy text" then it will throw exception
Please check content of file
Found the mistake, I used WriteLine instead of Write so it added enter on the end of the line which made the path incorrect, thanks for the help

Checking if two strings are equal

I want to check if a string from the first line of a file, is equal with an another string.
The awkward part is that, the strings are the same, but my program doesn't return a true value.
The string is teach and the first line of the file is teach too.
string date = System.IO.File.ReadAllText(folder + "/NPC/" + score_npc + "/" + score_npc + ".txt" );
if (condition)
{
string[] parametrii = date.Split('\n');
if (parametrii[0].Equals("teach"))
//instructions
I tried all the compare methods, i made my own function too. And my function said me that the (parametrii[0])[0] == b
Here is how the file looks like:
teach
poza1
poza2
end
That's propably because new line character is not \n in the file. It may be \r\n instead.
Try File.ReadAllLines instead:
string[] lines = System.IO.File.ReadAllLines(folder + "/NPC/" + score_npc + "/" + score_npc + ".txt" );
if (condition)
{
if (lines[0].Equals("teach"))
// instructions
}
Edit
As Grant Winney suggests, if you only need to manipulate first line (or not all of the) file, you may use File.ReadLines:
string firstLine = File.ReadLines(path).First();
instead.
Have u tried to change
string[] parametrii = date.Split('\n');
into
string[] parametrii = date.Split(Environment.NewLine);?
I suspect it's because your strings contain '\r' character

While reading text file, date format is changed in C#

I am reading a csv file which has following data format
14-Sep-12 ALUMINI 31-Dec-12 117.65 119.25 117.65 118.9 116.75 36
14-Sep-12 ALUMINI 30-Nov-12 116.95 118.65 116.8 118.4 116.5 252
14-Sep-12 ALUMINI 31-Oct-12 116.45 118.15 116.05 117.85 116.05 2802
I am reading this data with following code
List<string> sc = new List<string>();
filepath = "abc.csv" ;
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite);
StreamReader sr = new StreamReader(fs);
if (fs != null)
{
while ((oneLine = sr.ReadLine()) != null)
{
sc.Add(oneLine);
}
sr.Close();
// Now writing above data in some file , fo and fout are already declared
fo = new FileStream("tempd.txt", FileMode.Append, FileAccess.Write);
fout = new StreamWriter(fo);
foreach (string str in sc)
{
// i am using ' ' as one of my splitter character
char[] splitter = { ' ', ',', '\t' };
string[] sa1 = str.Split(splitter);
string wline = sa1[0] + "," + sa1[1] + "," + sa1[5] + "," + sa1[6] + "," + sa1[7] ;
fout.WriteLine(wline);
}
fout.Close();
}
My biggest problem is first column of of data is 14-Sep-2012 has been changed to 14 Sep 2012 (- is missing). Which is creating problem in my rest of application.
Is there any way by which I can convert date format while reading and writing file, I want to store this date 14-Sep-2012 as 2012-9-14.
I think this is the answer you are looking for.
DateTime d = Convert.ToDateTime(sa1[0]);
string wline = d.ToString("yyyy-MM-dd") + "," + sa1[1] + "," + sa1[5] + "," + sa1[6] + "," + sa1[7];
Your question doesn't make a lot of sense, so I'm going to make some assumptions here. First, you say that it's a CSV file. CSV stands for Comma Separated Values, but when you show the example - I see no commas at all. Am I right in thinking you have opened the CSV in Microsoft Excel and copied from there into your post?
If so, I then I would ask you to open your original CSV file in Notepad (or another text editor) instead. You will likely see then that your original data does not actually have the dashes.
Basically, when you provide a date in as 14 Sep 12 in your CSV file - Excel recognizes that this is a date, but then it formats it with its own default date format, which makes it look like 14-Sep-12 in Excel.
Another thing - you are reading the entire file into a list of strings, and then outputting the entire list back to a new file reformatted. Rather than load all of this in memory, why not just operate one line at a time? Open both your input and output files, read a line from input, manipulate it, and write it to output. Then loop to the next line and close both files when done. You will find this uses much less memory and generally runs faster.
If you want to reformat the dates, that's easy. Just parse the string into a date. Then control the output of your date with a string formatter in .ToString(). I belive Geethanga's answer shows this well, but Date.Parse() is usually preferred over Convert.ToDateTime().

Numeric fields lose leading zero while writing CSV in c#

I'm using an ASP.NET application which exports my clients data to CSV, I need my clients Phone number to be with the leading Zero.
I need the phone numbers to be without "-" and without quotations, and due to the nature of my application I cannot use 3rd party products such as EPPLUS.
I've tried to put a space and let the CSV "understand" that I need the phone number as text , but that doesn't seem right.
I would like to know how to make the excel include the leading zero , without using 3rd party products.
Thanks
Change the data that is saved in the csv with the following format:
="00023423"
CSV example:
David,Sooo,="00023423",World
This will show 00023423 in excel and not 23423.
public void CreatingCsvFiles(Client client)
{
string filePath = "Your path of the location" + "filename.csv";
if (!File.Exists(filePath))
{
File.Create(filePath).Close();
}
string delimiter = ",";
string[][] output = new string[][]{
new string[]{ "=\"" + client.phone + "\"", client.name }
};
int length = output.GetLength(0);
StringBuilder sb = new StringBuilder();
for (int index = 0; index < length; index++)
sb.AppendLine(string.Join(delimiter, output[index]));
File.AppendAllText(filePath, sb.ToString());
}
Inspired from http://softwaretipz.com/c-sharp-code-to-create-a-csv-file-and-write-data-into-it/
The important part :
"=\"" + client.phone + "\"", client.name
If the phone number is an int, of course you add .toString().
Print phone number to CSV with prepended ' (single quote), so it looks like:
"Some Name","'0000121212"
Excel should treat this 0000121212 as string then.
I believe converting the number into a formula like the accepted answer might not be a helpful solution for all.
The alternate solution I went with is to just add a tab space before the integer value.
Example:
Taking phoneNumber as a string variable which contains our int value
Solution:
"\t" + phoneNumber
If you know already how much numbers has to be inside phone you can do like this
phoneNumber.ToString("000000000000")
In this example I consider that phoneNumber is an int and required length of numbers is 12.

C# Create multiple .txt files using strings from another file and textbox

I am new to programming. Is there a way to create multiple .txt files using
data from another file in C#.
like this:
1. we have data.txt with 100 or more strings
string1
string2
string3
...
2. we have textbox1 and textbox2 waiting for user to enter strings
3 . we need to create 100 or more files using strings from data.txt and textboxes strings: name of the fisrt file : string1+textbox1string.txt
and inside it we write:
textbox2string + string1 + textbox1string
the same pattern to create other files, second - string2+textbox1string.txt and inside second - textbox2string + string2 + textbox1string
sorry for my english i am not native speaker.
Well, it sounds like you want something like:
string[] lines = File.ReadAllLines("file1.txt");
foreach (string line in lines)
{
File.WriteAllText(line + textbox1.Text + ".txt",
textbox2.Text + line + textbox1.Text);
}
Basically for very simple tasks like this, the methods in the File class allow "one shot" calls which read or write whole files at a time. For more complicated things you generally have to open a TextReader/TextWriter or a Stream.
If this wasn't what you were after, please provide more information. Likewise if you find the code hard to understand, let us know and we'll try to explain. You may fine it easier with more variables:
string[] lines = File.ReadAllLines("file1.txt");
foreach (string line in lines)
{
string newFile = line + textbox1.Text + ".txt";
string fileContent = textbox2.Text + line + textbox1.Text;
File.WriteAllText(newFile, fileContent);
}
EDIT: If you want to add a directory, you should use Path.Combine:
string newFile = Path.Combine(directory, line + textbox1.Text + ".txt");
(You can do it just with string concatenation, but Path.Combine is a better idea.)
Look into the static File class. It will have a lot of what you want.
http://msdn.microsoft.com/en-us/library/6ka1wd3w.aspx
Sure...
string textbox1string = textbox1.Text, textbox2string = textbox2.Text;
foreach(string line in File.ReadAllLines("data.txt")) {
string path = Path.ChangeExtension(line + textbox1string, "txt");
File.WriteAllText(path, textbox2string + line + textbox1string);
}

Categories

Resources