StreamReader C# - c#

While reading a text file(which contains the location of a file to be exported to a database) using the streamReader function in C#, how can I add a confirmation message to the code that will be displayed in the command prompt window(console application) so that I know the file got read and was exported?
public class Script
{
public static void Main(string[] args)
{
// Prepare the type that will handle all of the exporting needs
FileExporter exporter = new FileExporter();
try
{
//create an instance of StreamReader to read from a file.
//The using statemen also closes the StreamReader.
using (StreamReader sr = new StreamReader("ScriptFile.txt"))
{
string filePath;
//read and display lines from the file until the end of
//the file is reached.
while ((filePath = sr.ReadLine()) != null)
{
// Throw error if file does not exists to terminate the process.
if (!File.Exists(filePath))
{
string msg = string.Format("File not found at {0}.", filePath);
throw new FileNotFoundException(msg);
}
// Set the name of the export to be the name of the file.
string exportName = new FileInfo(filePath).Name;
// Export image as an SHP file if the extension matches.
if (filePath.Contains(".shp"))
{
exporter.processSHP(filePath, exportName, "");
//need confirmation that exporter.processSHP occured <<<-----***
}
else
{
string fileExtension = filePath.Split('.')[filePath.Split('.').Length - 1];
exporter.processIMG(filePath, exportName, "", fileExtension);
//need confirmation that exporter.processIMG occured <<<-----***
}
}
}
}
catch (Exception e)
{
Console.WriteLine(
string.Format("Process terminated. An error has occurred: {0}", e.ToString()));
}
}

Add this:
Console.WriteLine("Done reading & Exporting");
above
}
catch (Exception e)
{

Don't forget the Console.ReadKey() in case you want to actually see it up there

use flush and then close on your writer object.
then write done to console.

After you read the file to the end and look for your match (assuming you have something like a boolean value to let you know the export happened and a match was found) you can check the EndOfStream property in the streamreader and output the message. Or you can just check your match value to see if it returned true.

Related

Create the file if readalltext can't find it

I'm writing an application in visual studio using c#. I want to check if readalltext finds the file correctly, if not it needs to create the file and put a zero in it. In pseudocode:
if(x=File.ReadAllText("file.txt")==NULL)
{
File.WriteAllText("file.txt", "0");
x=File.ReadAllText("file.txt");
}
How can I do this? Thanks in advance, I tried some google but I may be inputting the wrong keywords
You can check whether a file exists with the File.Exists() method.
string path = "file.txt";
if (!File.Exists(path))
{
File.WriteAllText(path, "0");
}
The problem with using File.Exist() is that there is a risk the file is created or deleted after the check was made. The risk may be small, but may still need to be handled. One way to handle this would be with a try/catch inside a loop:
while (true)
{
try
{
if (!File.Exists(path))
{
File.WriteAllText(path, "0");
return "0";
}
else
{
return File.ReadAllText(path);
}
}
catch (IOException)
{
// try again
}
}
Another way would be to skip ReadAllText and instead open a fileStream. If that succeeds you know you have exclusive access to the file, to either read or write to it:
try
{
using var fs = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
if (fs.Length == 0)
{
using var sw = new StreamWriter(fs);
sw.Write('0');
return "0";
}
else
{
using var sr = new StreamReader(fs);
return sr.ReadToEnd();
}
}
catch (Exception)
{
// Handle the various types of exception that may occur.
}

C# error saving Excel file

I'm pretty new to C# and I'm experimenting a lot, I'm trying to make my program a little more user friendly and that is where the problem starts.
At first the location of the excelfile was in a public static string and I had no problems. I've changed it to this:
public string Excellocation()
{
string xlLocation;
if (but_Browse.Text == "Zoek Excel")
{
xlLocation = #"E:\Levi\Documents\Verjaardagen.xlsx";
}
else //Only if I get into this part of my code I get the error
{
xlLocation = but_Browse.Text;
}
return xlLocation;
}
And the button I use so the user can give me a location for the excel file is:
private void but_Browse_Click(object sender, EventArgs e)
{
var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string fileToOpen = FD.FileName;
System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName);
//OR
System.IO.StreamReader reader = new System.IO.StreamReader(fileToOpen);
//etc
but_Browse.Text = fileToOpen;
this.but_Browse.AutoSize = true;
But_Import.Visible = true;
}
}
Reading the Excel-file is no problem, my program finds it and processes it, if and only if the user changed the location by using the "Browse button" I get a message from Windows that there is already an excel file with that name and if I want to replace it, If I click away that message, my code gives an error on the line that tries to save the excel file
xlWorkbook.Save();
xlWorkbook.Close(true);
xlApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
xlWorkbook.Save() gives me this error:
System.Runtime.InteropServices.COMException occurred
HResult=0x800A03EC Message=Verjaardagen.xlsx can not be saved,
because it's read-only.
I have no idea why I don't get an error with the default location while I do get an error if use my button to give me that same location.
Does anyone know what i'm doing wrong?
Thanks in advance
So the problem is that the file is read only when you try to write to it after going through but_Browse_Click? Are you closing the StreamReader? Try using
reader.close();
in but_Browse_Click.
Perhaps a better way would be:
using (StreamReader reader = new StreamReader(fileToOpen))
{
//all code involving the reader in here
}
This automatically closes on completion.

WPF, C#, everytime the "Textrange.save"method can only save a ".text file" of 4096 bytes

These code seems worked before but I didn't have a backup, and now it comes with this problem that I really cant figure out why.
Purpose : I would like to log all the serial port content received from a COM port, into a .text file (or other extension, not important), using the typical TextRange.save(filestream, DataFormat.Text) method.
Here is the code on the side serial, I just make a copy of the serial date into a function that I save the content into files.
private void Recieve(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
// Collecting the characters received to our 'buffer' (string).
try
{
data_serial_recieved = serial.ReadExisting();
}
catch
{
//MessageBox.Show("Exception Serial Port : The specified port is not open.");
}
Dispatcher.Invoke(DispatcherPriority.Normal, new Delegate_UpdateUiText(WriteData), data_serial_recieved);
/* log received serial data into file */
Tools.log_serial(data_serial_recieved);
}
It is the only place that I use the function log_serial(string).
Here comes the code that I save string into file :
public static void log_serial(string input_text)
{
Paragraph parag = new Paragraph();
FlowDocument FlowDoc = new FlowDocument();
string text = input_text;
string filepath = Globals.savePath
+ "\\" + Globals.FileName_Main
+ ".text";
parag.Inlines.Add(text);
FlowDoc.Blocks.Add(parag);
try
{
using (FileStream fs = new FileStream(#filepath, FileMode.OpenOrCreate, FileAccess.Write))
{
TextRange textRange = new TextRange(FlowDoc.ContentStart, FlowDoc.ContentEnd);
textRange.Save(fs, DataFormats.Text);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I've tried, and there are no exceptions in this part.
Problem : everytime I run the code, the file I got at the end always has a size of 4096 bytes. Really cant figure out what is causing this error, anyone has a idea, please?
It seems that it may be a problem of privilege, but, the first time I use these code, I do remember that I got all the content output into a .text file. This is really weird to me. Any help?
You sure are doing a lot of extra work making a FlowDoc, etc.. just to end up writing the text passed in to a file. Besides that though, you are overwriting the file every time you call log_serial.
Here is a shorter version of your code that appends to (or creates) the output file:
public static void log_serial(string input_text)
{
string text = input_text;
string filepath = Globals.savePath
+ "\\" + Globals.FileName_Main
+ ".text";
try
{
using (var sw = System.IO.File.AppendText(filepath))
{
sw.WriteLine(input_text);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

Processing multiple drag and dropped files fails when using regular expressions

In my application the user can drag and drop multiple text files onto a GUI control to convert them to another format. Here is the relevant code:
private void panelConverter_DragDrop(object sender, DragEventArgs e)
{
string[] filenames = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string filename in filenames)
{
convertFile(filename);
}
}
private void convertFile(string filename)
{
// build name of output file
string convertedFile = Path.ChangeExtension(filename, ".out");
// open input file for reading
FileInfo source = new FileInfo(filename);
StreamReader srcStream = source.OpenText();
// open output file for writing
StreamWriter dstStream = new StreamWriter(convertedFile);
// loop over input file
string line;
do
{
// get next line from input file
line = srcStream.ReadLine();
if (!Regex.IsMatch(line, #"fred=\d+"))
{
dstStream.WriteLine(line);
dstStream.Flush();
}
} while (line != null);
}
The problem is that when I drop multiple files on the GUI, only one of them actually gets processed. I have found that if I comment out the Regex line, all of the dropped files are processed. Am I missing something in my handling of regular expressions in this context?
Try following variation of the method:
private void convertFile(string filename)
{
// build name of output file
string convertedFile = Path.ChangeExtension(filename, ".out");
// open input file for reading
FileInfo source = new FileInfo(filename);
StreamReader srcStream = source.OpenText();
// open output file for writing
using (StreamWriter dstStream = File.CreateText(convertedFile))
{
// loop over input file
string line;
do
{
// get next line from input file
line = srcStream.ReadLine();
if (!Regex.IsMatch(line, #"fred=\d+"))
{
dstStream.WriteLine(line);
dstStream.Flush();
}
} while (line != null);
}
Debug.WriteLine(string.Format("File written to: {0}", convertedFile));
}
The main modification is use of using keyword which would guarantee disposal and closing of the file resource. If problem is not still resolved then try followings:
Do you have any global exception handlers? Make sure you check Debug > Exceptions... so that Visual Studio automatically breaks on the line where exception is thrown. See this article on how-to.
Make sure files are written at correct places. If files have full path then the Debug.WriteLine statement above would tell you were the files are being written.
You should get at least 0 length file written on the disk if no exceptions are occurring.

get the value of notepad and put it inside the c# string?

Notepad:
Hello world!
How I'll put it in C# and convert it into string..?
So far, I'm getting the path of the notepad.
string notepad = #"c:\oasis\B1.text"; //this must be Hello world
Please advice me.. I'm not familiar on this.. tnx
You can read text using the File.ReadAllText() method:
public static void Main()
{
string path = #"c:\oasis\B1.txt";
try {
// Open the file to read from.
string readText = System.IO.File.ReadAllText(path);
Console.WriteLine(readText);
}
catch (System.IO.FileNotFoundException fnfe) {
// Handle file not found.
}
}
You need to read the content of the file, e.g.:
using (var reader = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read))
{
return reader.ReadToEnd();
}
Or, as simply as possible:
return File.ReadAllText(path);
make use of StreamReader and read the file as shown below
string notepad = #"c:\oasis\B1.text";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(notepad))
{
while (sr.Peek() >= 0)
{
sb.Append(sr.ReadLine());
}
}
string s = sb.ToString();
Use File.ReadAllText
string text_in_file = File.ReadAllText(notepad);
check this example:
// Read the file as one string.
System.IO.StreamReader myFile =
new System.IO.StreamReader("c:\\test.txt");
string myString = myFile.ReadToEnd();
myFile.Close();
// Display the file contents.
Console.WriteLine(myString);
// Suspend the screen.
Console.ReadLine();
Reading From a Text File (Visual C#), in this example # is not used when StreamReader is being called, however when you write the code in Visual Studio it will give the below error for each \
Unrecognized escape sequence
To escape this error you can write # before " that is at the beginning of your path string.
I shoul also mentioned that it does not give this error if we use \\ even if we do not write #.
// Read the file as one string.
System.IO.StreamReader myFile = new System.IO.StreamReader(#"c:\oasis\B1.text");
string myString = myFile.ReadToEnd();
myFile.Close();
// Display the file contents.
Console.WriteLine(myString);
// Suspend the screen.
Console.ReadLine();

Categories

Resources