InputFile and TextFieldParser to parse csv - c#

I can parse a CSV file by using the file path and TextFieldParser.
Now I'm trying to parse a CSV file received from InputFile component.
Here is what I tried:
var stream = e.File.OpenReadStream();
var memoryStream = new MemoryStream();
await stream.CopyToAsync(memoryStream);
stream.Close();
using (var parser = new TextFieldParser(memoryStream))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(";", ",");
while (!parser.EndOfData)
{
//Do something here
}
}
But when I run that, it does not enter the using block and never go further.
What should I do?
Thanks

use try-catch block for see Exceptions and error details.

Related

Is there a way to not generate a file via CSV Helper?

If the any opportunity to not generate csv file in system?
I don't wanna to store it in my application and can we generate it smth on fly?
As return I want to converted csv to base64.
var path = Path.Combine(Directory.GetCurrentDirectory(), "test.csv");
await using var writer = new StreamWriter(path);
await using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
await csv.WriteRecordsAsync(list);
}
var bytes = await File.ReadAllBytesAsync(path);
return Convert.ToBase64String(bytes);
A StreamWriter can write to any stream, including a MemoryStream:
using var ms=new MemoryStream();
using var writer = new StreamWriter(ms);
...
return Convert.ToBase64String(ms.GetBuffer());
CSV files are text files though, so converting them to BASE64 isn't very useful. StreamWriter uses UTF8 encoding by default so it already handles any language.
It would be better to keep the text as text, especially if it's going to be stored in a text field in a database. This can be done by reading the bytes using a StreamReader
using var reader=new StreamReader(ms);
ms.Position=0;
var csvText=reader.ReadToEnd();
var csvText

XML file from ZIP Archive is incomplete in C#

I've work with large XML Files (~1000000 lines, 34mb) that are stored in a ZIP archive. The XML file is used at runtime to store and load app settings and measurements. The gets loadeted with this function:
public static void LoadFile(string path, string name)
{
using (var file = File.OpenRead(path))
{
using (var zip = new ZipArchive(file, ZipArchiveMode.Read))
{
var foundConfigurationFile = zip.Entries.First(x => x.FullName == ConfigurationFileName);
using (var stream = new StreamReader(foundConfigurationFile.Open()))
{
var xmlSerializer = new XmlSerializer(typeof(ProjectConfiguration));
var newObject = xmlSerializer.Deserialize(stream);
CurrentConfiguration = null;
CurrentConfiguration = newObject as ProjectConfiguration;
AddRecentFiles(name, path);
}
}
}
}
This works for most of the time.
However, some files don't get read to the end and i get an error that the file contains non valid XML. I used
foundConfigurationFile.ExtractToFile();
and fount that the readed file stops at line ~800000. But this only happens inside this code. When i open the file via editor everything is there.
It looks like the zip doesnt get loaded correctly, or for that matter, completly.
Am i running in some limitations? Or is there an error in my code i don't find?
The file is saved via:
using (var file = File.OpenWrite(Path.Combine(dirInfo.ToString(), fileName.ToString()) + ".pwe"))
{
var zip = new ZipArchive(file, ZipArchiveMode.Create);
var configurationEntry = zip.CreateEntry(ConfigurationFileName, CompressionLevel.Optimal);
var stream = configurationEntry.Open();
var xmlSerializer = new XmlSerializer(typeof(ProjectConfiguration));
xmlSerializer.Serialize(stream, CurrentConfiguration);
stream.Close();
zip.Dispose();
}
Update:
The problem was the File.OpenWrite() method.
If you try to override a file with this method it will result in a mix between the old file and the new file, if the new file is shorter than the old file.
File.OpenWrite() doenst truncate the old file first as stated in the docs
In order to do it correctly it was neccesary to use the File.Create() method. Because this method truncates the old file first.

Create a valid PDF from a web request

I'm trying to create a scanning solution. Basically the user is physically scanning a page. The printer is making an API call, passing in the binary data of the scan in the body.
I'm trying to save this as a PDF on the server, but when I go to open the file, i'm getting an error "There is an error while reading a stream".
var bodyStream = new StreamReader(HttpContext.Current.Request.InputStream);
bodyStream.BaseStream.Seek(0, SeekOrigin.Begin);
var bodyText = bodyStream.ReadToEnd();
string pathToFiles = HttpContext.Current.Server.MapPath("~\\UploadedFiles\\WriteLines.pdf");
try
{
using (StreamWriter outputFile = new StreamWriter(pathToFiles, false))
{
outputFile.WriteLine(bodyText);
}
HttpContext.Current.Response.ContentType = "application/pdf";
}
catch (Exception ex)
{
throw (ex);
}
This is just testing something, and I have permissions etc for writing the file, it's just not creating a valid file.
Any thoughts on what I should use? I have looked into some libraries, but they don't seem to cover what i'm after
StreamReader.ReadToEnd convert bytes to string in particular encoding (UTF8 by default). I don't think this work for PDF.
You need copy bytes directly in the output file :
var bodyStream = HttpContext.Current.Request.InputStream;
bodyStream.Seek(0, SeekOrigin.Begin);
string pathToFiles = HttpContext.Current.Server.MapPath("~\\UploadedFiles\\WriteLines.pdf");
using (FileStream outputFile = File.Create(pathToFiles))
{
bodyStream.CopyTo(outputFile);
}

Writing data from textbox into text file

Here is the code im using to write and read from text file.
StreamWriter sw1 = new StreamWriter("DataNames.txt");
sw1.WriteLine(textBox1.Text);
sw1.Close();
StreamWriter sw2 = new StreamWriter("DataNumbers.txt");
sw2.WriteLine(textBox2.Text);
sw2.Close();
FileInfo file1 = new FileInfo("DataNames.txt");
StreamReader sr1 = file1.OpenText();
while (!sr1.EndOfStream)
{
listBox1.Items.Add(sr1.ReadLine());
}
FileInfo file2 = new FileInfo("DataNumbers.txt");
StreamReader sr2 = file2.OpenText();
while (!sr2.EndOfStream)
{
listBox2.Items.Add(sr2.ReadLine());
}
The thing is that when I click my button to save data from my textboxes to my text files an error appears that says "The process cannot access the file 'C:\xxxx\xxxxxx\xxxxx\xxxx\xxxxx\xxxxx.txt' because it is being used by another process."
Can anyone tell me why I have this error and maybe help me fix it
Try added a using statment around your streams to make sure they are Disposed otherwise the file is still locked to the stream
Example:
//Write
using (StreamWriter sw1 = new StreamWriter("DataNames.txt"))
{
sw1.WriteLine(textBox1.Text);
}
using (StreamWriter sw2 = new StreamWriter("DataNumbers.txt"))
{
sw2.WriteLine(textBox2.Text);
}
// Read
foreach (var line in File.ReadAllLines("DataNames.txt"))
{
listBox1.Items.Add(line);
}
foreach (var line in File.ReadAllLines("DataNumbers.txt"))
{
listBox2.Items.Add(line);
}
It appears you do not close the file after you read it. After you call FileInfo.OpenText you get a StreamReader which has to be closed, either via Close method, or even better, with a using statement.
But there are already methods that do all that for you, have a look at File.WriteAllText,
File.AppendAllText and File.ReadAllLines methods.
You need to Close the StreamReader object once you do not need it any more. This should fix this issue.
I.e.
StreamReader sr1 = file1.OpenText();
try {
while (!sr1.EndOfStream)
{
listBox1.Items.Add(sr1.ReadLine());
}
}
finally {
sr1.Close();
}
FileInfo file2 = new FileInfo("DataNumbers.txt");
StreamReader sr2 = file2.OpenText();
try {
while (!sr2.EndOfStream)
{
listBox2.Items.Add(sr2.ReadLine());
}
}
finally {
sr2.Close();
}
You have opened files but not closed.
StreamReader sr1 = file1.OpenText();
StreamReader sr2 = file2.OpenText();
Your problem occurs, because you are not closing the stream readers.
A safer way of using external resources (the files in this case) is to embed their use in a using statement. The using statement automatically closes the resource at the end of the statement block or if the statement block if left in another way. This could be a return statement or an exception, for instance. It is guaranteed that the resource will be closed, even after an exception occurs.
You can apply the using statement on any object which implements the IDisposable interface.
// Writing to the files
using (var sw1 = new StreamWriter("DataNames.txt")) {
sw1.WriteLine(textBox1.Text);
}
using(var sw2 = new StreamWriter("DataNumbers.txt")) {
sw2.WriteLine(textBox2.Text);
}
// Reading from the files
FileInfo file1 = new FileInfo("DataNames.txt");
using (StreamReader sr1 = file1.OpenText()) {
while (!sr1.EndOfStream) {
listBox1.Items.Add(sr1.ReadLine());
}
}
FileInfo file2 = new FileInfo("DataNumbers.txt");
using (StreamReader sr2 = file2.OpenText()) {
while (!sr2.EndOfStream)
{
listBox2.Items.Add(sr2.ReadLine());
}
}
However, you can simplify the reading part like this
// Reading from the files
listBox1.Items.AddRange(File.ReadAllLines("DataNames.txt"));
listBox2.Items.AddRange(File.ReadAllLines("DataNumbers.txt"));
I've seen this behavior before - usually there's another process open that's blocking the file access. Do you have multiple development servers open in your taskbar? (Strange, yes, but I've seen it happen)

StreamWriter is not able to write in file

My code is
System.IO.StreamWriter objStreamWriter = new System.IO.StreamWriter(File);
objStreamWriter.Write(txtEditor.Text);
objStreamWriter.Close();
txtEditor.Text = string.Empty;
I got a message The file has been modified out side of............. but my text file is empty. When in debug mode, I got a value of textEditor and path is not a problem. Am I missing some stupid things.
Thanks.
You have to verify the content of txtEditor before you write it to disk file.
string text=txtEditor.Text;
if(text.Trim.Length!=0)
{
using(System.IO.StreamWriter objStreamWriter = new System.IO.StreamWriter(File))
{
objStreamWriter.Write(text);
}
}
Use the StreamWriter by the "using" keyword for correct writing in to textfile.
using (StreamWriter writer = new StreamWriter("important.txt"))
{
writer.Write("Word ");
writer.WriteLine("word 2");
writer.WriteLine("Line");
}
Refer to the C# Using StreamWriter for more info

Categories