Application still says file is open and display error - c#

I have a txt file that is loaded into a listbox when the form loads. Im trying to get this button to add to the text file. It says the file is still open. Is there a way I can make this add the path of the file selected to the listbox even if open. I'm not sure how to close this. I've been told it automatically does it.
private void shortcutManagerForm_Load(object sender, EventArgs e)
{
if (File.Exists("Shortcut_Items.txt"))
{
shortcutListBox.DataSource = File.ReadAllLines("Shortcut_Items.txt");
}
}
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string tempPath = "";
tempPath = openFileDialog1.FileName;
StreamWriter file2 = new StreamWriter("Shortcut_Items.txt", true);
string path = "Shortcut_Items.txt";
string appendText = Environment.NewLine + tempPath + Environment.NewLine;
File.AppendAllText(path, appendText);
MessageBox.Show("Shortcut added");
}

StreamWriter file2 = new StreamWriter("Shortcut_Items.txt", true);
// ...
File.AppendAllText(path, appendText);
Sure, the file is open. You create a StreamWriter that opens that file for writing. Then - completely independently of that StreamWriter - you open the file for writing again using File.AppendAllText.
Get rid of your StreamWriter code entirely. If you're using File.AppendAllText, you don't need a StreamWriter - File.AppendAllText is self-contained.

You are never CLOSING the file. I would recommend the 'using' statement which will automatically close your file for you.
Replace this portion of your code:
StreamWriter file2 = new StreamWriter("Shortcut_Items.txt", true);
string path = "Shortcut_Items.txt";
string appendText = Environment.NewLine + tempPath + Environment.NewLine;
File.AppendAllText(path, appendText);
With this:
using(StreamWriter file2 = new StreamWriter("Shortcut_Items.txt", true))
{
//Do whatever you're going to do with the file
}
string path = "Shortcut_Items.txt";
string appendText = Environment.NewLine + tempPath + Environment.NewLine;
File.AppendAllText(path, appendText);

Related

Use affected file/directory to streamread to console

I'm trying to actively scan recent file inputs from a directory and StreamReading the file to console. I'm having problems finding a solution to using the most recent file input and printing the whole file text lines to console. I'm using FileSystemWatcher for recent inputs.
Here's my code (I'm a beginner):
private static void filesys_created(object sender, FileSystemEventArgs e)
{
Console.WriteLine(DateTime.Now + " : New file input: {0}", e.Name + Enviroment.Newline);
try
{
using (StreamReader sr = new StreamReader(directorypath))
{
string path = directorypath
String line = sr.ReadLine(e.Name);
string filename = e.Name;
Console.WriteLine(line);
}
}
catch (exception)
{
Console.WriteLine("File could not be read to console");
}
}
Only error showing is "No overload for method "ReadLine" takes 1 argument.
& File is not streamreading text to console
You must open the file from FullPath in FileSystemEventArgs
Then, you can write to console the content of the file by ReadToEnd
using (StreamReader sr = new StreamReader(e.FullPath))
{
Console.WriteLine(sr.ReadToEnd());
}

how do i start with fresh with a new file

I catch an exception in my code for a wrong file type. Then i would like to change my file and use the correct file. How do i close the execption to look fresh at the new file and process it.
below is my code. one is a main function. the second is a called function.
main function.
//data file process button
private void button9_Click(object sender, EventArgs e)
{
try
{
panel1.Visible = false; // File paths (Admin Access))
panel3.Visible = true; // File process status
label6.Visible = true; // label - File process status
panel4.Visible = false; // Admin authenticate
InitializeFile();
ParseListFileData();
ListArrayFileData();
CleanDesiredData();
GetRRData();
GetLecoData();
//cleanup();
textBox5.Text += "All RR & Leconum data processing from file - " + textfilename + " completed." + "\r\n";
textBox5.Text += "Please click EXIT to close HORIBA program" + "\r\n";
}
catch(IndexOutOfRangeException)
{
//cleanup();
textBox5.Text += "Bad File" + "\r\n";
datafilepath = "";
textBox5.Text += "Select correct file" + "\r\n";
}
}
The Called Function ParseListFileData();
public void ParseListFileData()
{
//Opens file and uses for processing
System.IO.StreamReader sr = new
System.IO.StreamReader(datafilepath);
try
{
//while loop to read file till end of file
while (!sr.EndOfStream)
{
//split data in file into differend fields
var Row = sr.ReadLine();
var values = Row.Split(',');
ColmnA.Add(values[0]);
ColmnB.Add(values[1]);
ColmnC.Add(values[2]);
ColmnD.Add(values[3]);
ColmnE.Add(values[4]);
ColmnF.Add(values[5]);
ColmnG.Add(values[6]);
ColmnH.Add(values[7]);
ColmnI.Add(values[8]);
ColmnJ.Add(values[9]);
ColmnK.Add(values[10]);
ColmnL.Add(values[11]);
ColmnM.Add(values[12]);
ColmnN.Add(values[13]);
}
sr.Close();
sr.Dispose();
}
catch (IndexOutOfRangeException e)
{
sr.Close();
sr.Dispose();
datafilepath = "";
//cleanup();
//print(e.Message.("Error encountered");
textBox5.Text += "File type not correct or missing data in file "+ e + "\r\n";
}
}
As soon as i select a new good working file, the old exception seems closed, but the old file still remains in use and shows an exception at another function. Even though i i use dispose() to close the streamreader resources.
How can i start fresh with a new file.
Im not sure what exactly is the problem, is the file handle not closed.
I see a problem with your code: you try and catch, but only on a specific exception, say you get an ArgumentException, this will not be caught, instead you can use try{}catch{}finaly{}
try
{
/blabla
}
catch (IndexOutOfRangeException e)
{
datafilepath = "";
//cleanup();
//print(e.Message.("Error encountered");
textBox5.Text += "File type not correct or missing data in file "+ e + "\r\n";
}
finaly
{ //this codes always runs wether exception or not.
sr.Close();
sr.Dispose();
}
alternative and easier solution is to use using (which closes disposables automatically when done):
using(var sr = new System.IO.StreamReader(datafilepath);) {
//try catch in here. even is something goes horribly wrong. StreamReader = fileHandle will be closed.
}

How to save and read text file using File.ReadAllText() from application startup?

I'm saving a text file at application startup and reading this text file from application startup.
This is not saving my file at application startup, what's wrong with this code?
Saving text file at application startup code.
private void Savebutton1_Click(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(Application.StartupPath + "Book.txt", true);
string json = JsonConvert.SerializeObject(vals);
sw.Write(json);
MessageBox.Show("Book Saved Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
loading text file from application startup code.
string path = Path.Combine(Application.StartupPath, "ChequeBook.txt");
string textholder;
try
{
// Use StreamReader to consume the entire text file.
using (StreamReader reader = new StreamReader(path))
{
MessageBox.Show("Reached Here");
textholder = reader.ReadToEnd();
MessageBox.Show("Reached Here - 2");
}
if (textholder == string.Empty) {
return;
}
// Deserialise it from Disk back to a Dictionary
string jsonToRead = File.ReadAllText(textholder);
List<KeyValuePair<int, string>> myDictionaryReconstructed =
JsonConvert.DeserializeObject<List<KeyValuePair<int, string>>>(jsonToRead);
I wanted to save & write text file in application folder using File.CreateText method.
Found the First Answer:
This will write and save the text file in application folder.
using (StreamWriter sw = File.CreateText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Book.txt")))
{
string json = JsonConvert.SerializeObject(vals);
sw.Write(json);
}
MessageBox.Show("Book Saved Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
I wanted to read the text file from application folder.
This will read the contents of the text file from application folder.
string jsonToRead = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Book.txt"));

Saving a currently opened file without prompts

I am experiencing a problem with saving a currently opened file without it popping up the dialog asking what name to save it under.
To clarify myself a little more, I open a .txt file and work with it, then would like to just click 'Save' and it save the file without popping up a 'Save As' dialog box.
Here is my save code:
private void SaveFile()
{
SaveFileDialog fileChooser = new SaveFileDialog();
fileChooser.Title = "Choose Save Location";
fileChooser.Filter = "Text Files (*.txt)|*.txt";
fileChooser.OverwritePrompt = false; //Removes warning
DialogResult result = fileChooser.ShowDialog();
if (result == DialogResult.Cancel)
{
return;
}
try
{
string fileName = fileChooser.FileName;
output = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
fileWriter = new StreamWriter(output);
foreach (Employee emp in employee)
{
fileWriter.WriteLine(emp.Firstname + "," + emp.Lastname + "," + emp.Position + "," + emp.Bmonth + "," + emp.Bday + "," + emp.BYear + "," + emp.Salary + "," + emp.Hiremonth + "," + emp.Hireday + "," + emp.Hireyear);
}
fileWriter.Close();
output.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
fileWriter.Close();
output.Close();
}
}
Everything works great as far as saving it to a .txt file and loading it back in, it's just that popup that irks me.
The fileChooser object is a SaveFileDialog object. You're causing it to display by calling:
DialogResult result = fileChooser.ShowDialog();
If you don't want to show the dialog, just omit the fileChooser code and instead use:
string fileName = strAlreadyKnownFileName;
I'd firstly save the full path of the opened file in some variable lets say:
private string filepath = "path/to/my/file";
Then you need to create a button and call it i.e. "Save" double click on the button and write this simple code to save whatever you want to the current opened file:
as simple as that...
EDIT:
private void SaveFile()
{
//do your loop and stuff in here and finally write your text to the file using this
File.WriteAllText(filepath, yourtexttobesaved);
}

openfiledialog error for selecting used files

try
{
OpenFileDialog dialog = new OpenFileDialog();
String appData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string tempPath = System.IO.Path.GetTempPath();
dialog.InitialDirectory = tempPath;
dialog.Multiselect = true;
dialog.Filter = "Temp files (*.tmp)|*.tmp";
dialog.ValidateNames = false;
if (dialog.ShowDialog() == DialogResult.OK)
{
string[] filePaths = dialog.SafeFileNames;
foreach (string s in filePaths)
richTextBox1.Text += s;
//MessageBox.Show("");
}
}
catch
{
MessageBox.Show("Error Occured");
}
when i selecting files (which already in use in another application) in openfiledialog I getting error but still I want their paths...
This is apparantly an issue with OpenFileDialog and MultiSelect "true." See this post for a discussion on the problem (and some possible solutions):
http://social.msdn.microsoft.com/forums/en-US/netfxbcl/thread/56fbbf9b-31d5-4e89-be85-83d9cb1d538c/
Setting openFileDialog.ValidateNames = false; worked for me.
try
String tempPath = System.IO.Path.GetDirectoryName(dialog.FileName) + #"\";

Categories