how to clear txt file when you exit your application c# - c#

this is my code to fill my txt file, and show in my application.
StreamWriter file = new StreamWriter("opslag_kentekens",true);
string opslag_kentekens = textBox1.Text;
file.WriteLine(opslag_kentekens);
file.Close();
label20.Text = File.ReadAllText("opslag_kentekens");
My question is: how do i clear my txt file when i exit my application?

Clearing of text file is pretty straightforward: just write empty string into it:
StreamWriter file = new StreamWriter("opslag_kentekens", false);
file.Write(String.Empty);
file.Close();
Catching application exit depends on framework you're using in your application.
For example, on WinForms (it looks like you're using it) you can override OnFormClosed method of your main application form and to your file clearing there:
protected override void OnFormClosed(FormClosedEventArgs e)
{
base.OnFormClosed(e);
//clear your file
}
Or you can handle Application.ApplicationExit event and clear your file from there.

Related

C# open a pdf file using default application and delete the file after application is closed

I am converting a .txt file to a pdf and need to display the pdf to the user. For that, I have created a temporary .pdf file and created a process to open the file. This works fine when there is adobe acrobat installed. This fails when there is no default application. For my case, the pdf is opened in internet explorer and I get No process is associated with this object exception. Is there any other way to find out when the file is being closed so that I can delete it later on.
My code is like this.
HtmlToPdf htmlToPdf = new HtmlToPdf(pdfPrintOptions);
string tmpFileName = "zx" + DateTime.Now.Ticks + "x.pdf";
//Iron pdf does not handle in-memory pdf viewing
//convert it to pdf
htmlToPdf.RenderHTMLFileAsPdf(fileWithPath).SaveAs(tmpFileName);
// TempFileCollection tmpFileCollection = new TempFileCollection();
//Use windows process to open the file
Process pdfViewerProcess = new Process
{
EnableRaisingEvents = true, StartInfo = {FileName = tmpFileName}
};
pdfViewerProcess.Start();
pdfViewerProcess.WaitForExit(); **Failing in this line**
//Delete temporary file after the viewing windows is closed
if (File.Exists(tmpFileName))
{
File.Delete(tmpFileName);
}
Similar questions do not seem to provide a workaround for this problem. Any help will be appreciated. Thanks.
You have to define tmpFileName in global variable and use Event Exited like this:
try{
Process myProcess = new Process();
myProcess.StartInfo.FileName = tmpFileName;
myProcess.EnableRaisingEvents = true;
myProcess.Exited += new EventHandler(myProcess_Exited);
myProcess.Start();
}
catch (Exception ex){
//Handle ERROR
return;
}
// Method Handle Exited event.
private void myProcess_Exited(object sender, System.EventArgs e){
if (File.Exists(tmpFileName))
{
File.Delete(tmpFileName);
}
}
Hope it can help you
Update my answers:
If it still not working. Try this answers
I would just save the PDF file in the TEMP folder.
Either in Windows User TEMP folder or your App can create a TEMP folder. If you create a TEMP folder just delete every file when your app closed.
string filePath = Path.GetTempPath() + "yourfile.pdf";
//Writer your file to Path
//File.WriteAllBytes(filePath, content);
Process.Start(filePath);

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.

Cannot access LocalFolder files on Windows phone app (UnauthorizedAccessException)

I am trying to get an application to write (then read) a simple text file in Windows Phone 8. My app has three controls: a create file button, a display file button, and a textbox where the contents are supposed to display.
I have the following events set up in my code:
private async void btnCreateFile_Click(object sender, RoutedEventArgs e)
{
await ApplicationData.Current.LocalFolder.CreateFileAsync("myFile.txt");
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("myFile.txt");
StreamWriter writer = new StreamWriter(await file.OpenStreamForWriteAsync());
writer.WriteLine("Hello World");
writer.WriteLine("Goodbye world");
}
private async void btnShowFile_Click(object sender, RoutedEventArgs e)
{
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("myFile.txt");
StreamReader reader = new StreamReader(await file.OpenStreamForReadAsync());
string text = reader.ReadToEnd();
text1.Text = text;
}
}
The application is throwing UnauthorizedAccessException when the StreamReader is being created. Can anyone shed any light on why?
I guess you're not disposing the StreamWriter. See the example on MSDN.
using( var writer = new StreamWriter(await file.OpenStreamForWriteAsync()))
{
writer.WriteLine("Hello World");
writer.WriteLine("Goodbye world");
}
That's why your can't read the file, because it's already taken by SreamWriter.
Always use 'using' statement when using an object that inherits from IDisposable.
You are trying to write to an already opened file and this gives you UnauthoritedException.
Try using your code block inside of using.Check out this question to find more about StreamWriter :
how to use StreamWriter class properly?

Saving data from textboxes into text file

I am trying to write a program to me should be a lot easier than it is proving.
I have a form with text boxes that asks the user to enter their details e.g. Name, Address etc.. What I am trying to achieve is to save the data from the text boxes into a .txt file when the user hits the save button.
I am able to create the file but the data will not save into the file.
I have posted my code below, and any help you may have will be greatly appreciated.
private void btnSave_Click(object sender, EventArgs e)
{
string file_name = "e:\\test1.txt";
System.IO.StreamWriter objWriter;
objWriter = new System.IO.StreamWriter(file_name, true);
objWriter.Write(txtName.Text);
objWriter.Write(txtAddress.Text);
objWriter.Write(txtEmail.Text);
objWriter.Write(txtPhone.Text);
MessageBox.Show("Details have been saved");
}
It would be more practical to use using at the beginning of the code line where StreamWriter is present. This is to ensure data are Disposed, you'll need this to unlock the data from the stream.
When writing data:
using (StreamWriter objWriter = new StreamWriter("test1.txt"))
{
objWriter.Write(txtName.Text);
objWriter.Write(txtAddress.Text);
objWriter.Write(txtEmail.Text);
objWriter.Write(txtPhone.Text);
MessageBox.Show("Details have been saved");
}
When reading saved data, let's use a listbox just to have an example:
foreach (var line in File.ReadAllLines("test1.txt"))
{
listBox1.Items.Add(line);
}
Hope this helps!
It is a good practice to wrap local variables implementing IDisposable into the using statement:
using (StreamWriter objWriter = new StreamWriter(file_name, true))
{
objWriter.Write(txtName.Text);
objWriter.Write(txtAddress.Text);
objWriter.Write(txtEmail.Text);
objWriter.Write(txtPhone.Text);
}
This also has a positive side effect: the stream is flushed and closed right after execution of the using statement.
Suggestion: Consider using WriteLine instead of Write, because probably you need a delimiter between string values.
Call StreamWriter.Flush method after you done:
objWriter.Flush();
Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.
You could also do this using File.WriteAllText method:
var line = string.Join(" ", txtName.Text, txtAddress.Text, txtEmail.Text,txtPhone.Text);
File.WriteAllText(file_name, line);

C#: Windows App Reading CSV file and Writing to a Console Issue

I have a Windows Forms app that is able to launch a console for debuggin. In the app, through a menu click, I read a CSV file and write it to the console. The function that does this is below.
protected void menuRead_Click(object sender, EventArgs e)
{
// ... functionality to load CSV files
System.IO.Stream inputDataFile = null;
OpenFileDialog fd = new OpenFileDialog();
fd.InitialDirectory = "c:\\";
fd.Filter = "csv files (*.csv)|*.csv|All files (*.*)|*.*";
fd.FilterIndex = 1;
fd.RestoreDirectory = true;
if (fd.ShowDialog() == DialogResult.OK)
{
try
{
if ((inputDataFile = fd.OpenFile()) != null)
{
inputData_exists = true;
// ... read input data from CSV file
using (CsvFileReader reader = new CsvFileReader(inputDataFile))
{
CsvRow row = new CsvRow();
while (reader.ReadRow(row))
{
foreach (string s in row)
{
Console.Write(s);
Console.Write(" ");
}
Console.WriteLine();
}
// ... close the input data stream
inputDataFile.Close();
}
}
}
catch (Exception err)
{
//Inform the user if can't read the file
MessageBox.Show(err.Message);
}
}
}
Everything works fine except the following:
The csv file has about 1200 lines of code. When this code is executed, the OpenFileDialog() window only closes partially before the csv file contents begin to get written to the console window. So, I can see the data writing to the console window, and I have a small rectangular portion of the dialog window showing on my form. Is there any way to ensure the dialog is closed before the data is written to the console? Should I open anew thread to communicate with the console? Any advise or help woulf be greatly appreciated. Thank you.
You need to give some time for your control "OpenFileDialog" to repaint itself during dispose of the control, the easiest way for WinForm is to use Application.DoEvents()
if (fd.ShowDialog() == DialogResult.OK)
{
Application.DoEvents();
...
...
}
Your issue comes from the fact you display the console and your ShowDialog call. Get the result of the of Dialog then open your console application. You can also read the file on another thread I suppose.
You may use a lot of approaches here.
The simplest one:
Use StringBuilder and than put all data at once.
Because output to console may be quite slowly.
StringBuilder consoleBuffer = new StringBuilder();
using (CsvFileReader reader = new CsvFileReader(inputDataFile))
{
CsvRow row = new CsvRow();
while (reader.ReadRow(row))
{
foreach (string s in row)
{
consoleBuffer.Append(s);
consoleBuffer.Append(" ");
}
consoleBuffer.Append(Environment.NewLine);
}
Console.WriteLine(consoleBuffer.ToString());
// ... close the input data stream
inputDataFile.Close();
}

Categories

Resources