How can i get to the next column with FileStream? - c#

I want to write data to a csv file. But i can only get to the next row, not to the next column. I hope some people here know how to get to the next column.
String fileName = "C:\\Users\\hogen\\Desktop\\test.csv";
FileStream fileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
string columnTitles = "test, test \n test \n test";
fileStream.Write(Encoding.ASCII.GetBytes(columnTitles), 0, columnTitles.Length);
fileStream.Close();
I get now:
test, test
test
test
in the csv file. How do i get the second test of the first row in the next column?
Maybe if u guys know this, could maybe give some good examples of reading columns with filestream?

I think you're asking how to skip a column?
If you want a blank column, just add another comma: test,,test - make sure there are no spaces or other characters between the two commas.

No it doesn't seperate..
I found also this tutorial:
String fileName = "C:\\Users\\hogen\\Desktop\\test1.csv";
StringBuilder content = new StringBuilder();
content.AppendLine("name, age");
content.AppendLine("nick, 26");
File.AppendAllText(fileName, content.ToString());
Output:
https://i.stack.imgur.com/AWxMG.png

Related

Need to add empty space using StreamReader

I am reading all the files, using StreamReader and i need to insert empty space at the end of each line.
For Example : Consider below case, are the data in file.
File.........................................................................
New..........................................................................
Text.........................................................................
.............................................................................
In the dotted area, i need to include empty spaces. How can this be done?
I don't really understand your question, but, if the goal is to add spaces after any line , you can calculate the length of your line and then use this code to fill your line with the spaces needed :
var streamReaderFileName = new StreamReader(fileName, Encoding.Default);
var streamWriterNewName = new StreamWriter(newName, false, Encoding.GetEncoding(1252));
yourLine = streamReaderFileName.ReadLine();
while (yourLine!=null)
{
yourLineLength = yourLine.Length;
yourNewLine = yourLine.PadRight(yourLineLength + numberOfSpaceYouWant)
yourLine = streamReaderFileName.ReadLine();
}
streamWriterNewName.WriteLine(yourNewLine);
streamReaderFileName.Close();
streamWriterNewName.Close();
If you give us more info, maybe I could help better :)

C# so I need to split out a string, I think

so I have this application that I have inherited from someone that is long gone. The gist of the application is that it reads in a .cvs file that has about 5800 lines in it, copies it over to another .cvs, which it creates new each time, after striping out a few things , #, ', &. Well everything works great, or it has until about a month ago. so I started checking into it, and what I have found so far is that there are about 131 items missing from the spreadsheet. Now I read someplace that the maximun amount of data a string can hold is over 1,000,000,000 chars, and my spreadsheet is way under that, around 800,000 chars, but the only thing I can think is doing it is the string object.
So anyway, here is the code in question, this piece appears
to both read in from the existing field, and output to the new file:
StreamReader s = new StreamReader(File);
//Read the rest of the data in the file.
string AllData = s.ReadToEnd();
//Split off each row at the Carriage Return/Line Feed
//Default line ending in most windows exports.
//You may have to edit this to match your particular file.
//This will work for Excel, Access, etc. default exports.
string[] rows = AllData.Split("\r\n".ToCharArray(), System.StringSplitOptions.RemoveEmptyEntries);
//Now add each row to the DataSet
foreach (string r in rows)
{
//Split the row at the delimiter.
string[] items = r.Split(delimiter.ToCharArray());
//Add the item
result.Rows.Add(items);
}
If anyone can help me I would really appreciate it. I either need to figure out how to split the data better, or I need to figure out why it is cutting out the last 131 lines from the existing excel file to the new excel file.
One easier way to do this, since you're using "\r\n" for lines, would be to just use the built-in line reading method: File.ReadLines(path)
foreach(var line in File.ReadLines(path))
{
var items = line.Split(',');
result.Rows.Add(items);
}
You may want to check out the TextFieldParser class, which is part of the Microsoft.VisualBasic.FileIO namespace (yes, you can use this with C# code)
Something along the lines of:
using(var reader = new TextFieldParser("c:\\path\\to\\file"))
{
//configure for a delimited file
reader.TextFieldType = FieldType.Delimited;
//configure the delimiter character (comma)
reader.Delimiters = new[] { "," };
while(!reader.EndOfData)
{
string[] row = reader.ReadFields();
//do stuff
}
}
This class can help with some of the issues of splitting a line into its fields, when the field may contain the delimiter.

Writing fixed length strings on to file ....?

My client requirment has fixed length file records in the format of header, body and footer but in the footer they wants to have an empty space of 1966 lenght . I tried this using difffent butttons for header and footer and body but was unable to specify space at the end. this was my code .. space is not working in this while creating footer.
FileStream fs = new FileStream(#"C:\Users\IT-Administrator\Desktop\ee.txt", FileMode.Open, FileAccess.ReadWrite);
fs.Seek(0, SeekOrigin.End);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(comboBox6.Text + textBox2.Text + textBox3.Text + textBox4.Text + **SPACE(1966)** );
sw.Close();
fs.Close();**strong text**
Use String.PadRight() to pad the string.
Say for example the max string length was 2000 characters, you can do something like this:
string example = "Example";
string full_example = example.PadRight(2000);
This will take the length of the original string and pad it out with spaces until it reaches the desired width.
In your case if you wanted exactly 1966 spaces though you can do this:
string spaces = String.Empty.PadRight(1966);
You can do this by using the overload of WriteLine that accepts a format specifier.
If you want the last element to take a total of 1966 characters, you can write :
using(var sw=new StreamWriter(#"C:\Users\IT-Administrator\Desktop\ee.txt"))
{
sw.WriteLine("{0}{1}{2}{3,-1966}",comboBox6.Text ,textBox2.Text,
textBox3.Text,textBox4.Text );
}
This way it's much easier to see what the actual string will look like. For example, you can see that you are actually joining all elements in one continuous string. Perhaps, what you wanted to do was to separate them by spaces, eg: "{0} {1} {3} {4,-1966}"
If you want the the last element to be followed by 1966 spaces:
using(var sw=new StreamWriter(#"C:\Users\IT-Administrator\Desktop\ee.txt"))
{
sw.WriteLine("{0}{1}{3}{4}{5,-1966}",comboBox6.Text ,textBox2.Text,
textBox3.Text,textBox4.Text,' ');
}
In the above code, using makes sure the StreamWriter will close even if an exception occurs. The code also avoids creating both a StreamWriter and FileStream by creating the StreamWriter with a path argument
If you want to create a string consisting of 1966 spaces, you can use the string constructor that takes a character and a number of times to repeat it: new String(' ', 1966).
If you want to pad strings out to a particular length, you can use PadRight or PadLeft as appropriate.

How to read a file into a string with CR/LF preserved?

If I asked the question "how to read a file into a string" the answer would be obvious. However -- here is the catch with CR/LF preserved.
The problem is, File.ReadAllText strips those characters. StreamReader.ReadToEnd just converted LF into CR for me which led to long investigation where I have bug in pretty obvious code ;-)
So, in short, if I have file containing foo\n\r\nbar I would like to get foo\n\r\nbar (i.e. exactly the same content), not foo bar, foobar, or foo\n\n\nbar. Is there some ready to use way in .Net space?
The outcome should be always single string, containing entire file.
Are you sure that those methods are the culprits that are stripping out your characters?
I tried to write up a quick test; StreamReader.ReadToEnd preserves all newline characters.
string str = "foo\n\r\nbar";
using (Stream ms = new MemoryStream(Encoding.ASCII.GetBytes(str)))
using (StreamReader sr = new StreamReader(ms, Encoding.UTF8))
{
string str2 = sr.ReadToEnd();
Console.WriteLine(string.Join(",", str2.Select(c => ((int)c))));
}
// Output: 102,111,111,10,13,10,98,97,114
// f o o \n \r \n b a r
An identical result is achieved when writing to and reading from a temporary file:
string str = "foo\n\r\nbar";
string temp = Path.GetTempFileName();
File.WriteAllText(temp, str);
string str2 = File.ReadAllText(temp);
Console.WriteLine(string.Join(",", str2.Select(c => ((int)c))));
It appears that your newlines are getting lost elsewhere.
This piece of code will preserve LR and CR
string r = File.ReadAllText(#".\TestData\TR120119.TRX", Encoding.ASCII);
The outcome should be always single string, containing entire file.
It takes two hops. First one is File.ReadAllBytes() to get all the bytes in the file. Which doesn't try to translate anything, you get the raw data in the file so the weirdo line-endings are preserved as-is.
But that's bytes, you asked for a string. So second hop is to apply Encoding.GetString() to convert the bytes to a string. The one thing you have to do is pick the right Encoding class, the one that matches the encoding used by the program that wrote the file. Given that the file is pretty messed up if it contains \n\r\n sequences, and you didn't document anything else about the file, your best bet is to use Encoding.Default. Tweak as necessary.
You can read the contents of a file using File.ReadAllLines, which will return an array of the lines. Then use String.Join to merge the lines together using a separator.
string[] lines = File.ReadAllLines(#"C:\Users\User\file.txt");
string allLines = String.Join("\r\n", lines);
Note that this will lose the precision of the actual line terminator characters. For example, if the lines end in only \n or \r, the resulting string allLines will have replaced them with \r\n line terminators.
There are of course other ways of acheiving this without losing the true EOL terminator, however ReadAllLines is handy in that it can detect many types of text encoding by itself, and it also takes up very few lines of code.
ReadAllText doesn't return carriage returns.
This method opens a file, reads each line of the file, and then adds each line as an element of a string. It then closes the file. A line is defined as a sequence of characters followed by a carriage return ('\r'), a line feed ('\n'), or a carriage return immediately followed by a line feed. The resulting string does not contain the terminating carriage return and/or line feed.
From MSDN - https://msdn.microsoft.com/en-us/library/ms143368(v=vs.110).aspx
This is similar to the accepted answer, but wanted to be more to the point. sr.ReadToEnd() will read the bytes like is desired:
string myFilePath = #"C:\temp\somefile.txt";
string myEvents = String.Empty;
FileStream fs = new FileStream(myFilePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
myEvents = sr.ReadToEnd();
sr.Close();
fs.Close();
You could even also do those in cascaded using statements. But I wanted to describe how the way you write to that file in the first place will determine how to read the content from the myEvents string, and might really be where the problem lies. I wrote to my file like this:
using System.Reflection;
using System.IO;
private static void RecordEvents(string someEvent)
{
string folderLoc = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!folderLoc.EndsWith(#"\")) folderLoc += #"\";
folderLoc = folderLoc.Replace(#"\\", #"\"); // replace double-slashes with single slashes
string myFilePath = folderLoc + "myEventFile.txt";
if (!File.Exists(myFilePath))
File.Create(myFilePath).Close(); // must .Close() since will conflict with opening FileStream, below
FileStream fs = new FileStream(myFilePath, FileMode.Append);
StreamWriter sr = new StreamWriter(fs);
sr.Write(someEvent + Environment.NewLine);
sr.Close();
fs.Close();
}
Then I could use the code farther above to get the string of the contents. Because I was going further and looking for the individual strings, I put this code after THAT code, up there:
if (myEvents != String.Empty) // we have something
{
// (char)2660 is ♠ -- I could have chosen any delimiter I did not
// expect to find in my text
myEvents = myEvents.Replace(Environment.NewLine, ((char)2660).ToString());
string[] eventArray = myEvents.Split((char)2660);
foreach (string s in eventArray)
{
if (!String.IsNullOrEmpty(s))
// do whatever with the individual strings from your file
}
}
And this worked fine. So I know that myEvents had to have the Environment.NewLine characters preserved because I was able to replace it with (char)2660 and do a .Split() on that string using that character to divide it into the individual segments.

ASCII raw symbols to control a printer from a .txt file

A label printer is controled by sending a string of raw ASCII characters (which formats a label). Like this:
string s = "\x02L\r" + "D11\r" + "ySWR\r" + "421100001100096" + date + "\r" + "421100002150096" + time + "\r" + "421100001200160" + price + "\r" + "E\r";
RawPrinterHelper.SendStringToPrinter(printerName, s);
This hardcoded variant works well.
Now I want to put the control string to a .txt file and read it during runtime. Like this:
string printstr;
TextReader tr = new StreamReader("print.txt");
printstr = tr.ReadLine();
tr.Close();
But in this case printer prints nothing.
It seems, that StreamReader adds something else to this string
(If I put the read string to a MessageBox.Show(printstr); everything looks OK. Though, this way we can not see control characters added).
What could be a solution to this problem?
Your code calls tr.ReadLine() once, but it looks like you have multiple lines in that string.
Looks like a Zebra label printer, I've had the displeasure. The first thing you need to fix is the way you generate the print.txt file. You'll need to write one line for each section of the command string that's terminated with \r. For example, your command string should be written like this:
printFile.WriteLine("\x02L");
printFile.WriteLine("D11");
printFile.WriteLine("ySWR");
printFile.WriteLine("421100001100096" + date);
printFile.WriteLine("421100002150096" + time);
printFile.WriteLine("421100001200160" + price);
printFile.WriteLine("E");
printFile.WriteLine();
Now you can use ReadLine() when you read the label from print.txt. You'll need to read multiple lines to get the complete label. I added a blank line at the end, you could use that when you read the file to detect that you got all the lines that creates the label. Don't forget to append "\r" again when you send it to the printer.
It could be that the StreamReader is reading it in an Unicode format. By the way, you are reading in only just one line...you need to iterate the lines instead...Your best bet would be to do it this way:
string printstr;
TextReader tr = new StreamReader("print.txt",System.Text.Encoding.ASCII);
printstr = tr.ReadToEnd();
tr.Close();
Or read it as a binary file and read the whole chunk into a series of bytes instead, error checking is omitted.
System.IO.BinaryReader br = new System.IO.BinaryReader(new StreamReader("print.txt", System.Text.Encoding.ASCII));
byte[] data = br.ReadBytes(br.BaseStream.Length);
br.Close();
Edit:
After rem's comment I thought it best to include this additional snippet here...this follows on from the previous snippet where the variable data is referenced...
string sData = System.Text.Encoding.ASCII.GetString(data);
Hope this helps,
Best regards,
Tom.

Categories