I am having a problem with some filewatcher events. The filewatcher has 4 events. Created, Changed, Deleted, Renamed. Now my Created event works fine, but the rest doesn't although the application does run the events. I made it so when the created event is activated, the file in the 1st directory will automatically be copied to the 2nd directory. And so on with the rest of the events(File in 1st directory deleted, automatically delete in the 2nd directory). Like for example, this is my Deleted Event:
private void fileSystemWatcher1_Deleted(object sender, FileSystemEventArgs e)
{
if (!pause)
{
filepath = Path.Combine(source, e.Name);
name = Path.GetFileNameWithoutExtension(filepath);
File.Delete (target + e.Name); // Delete file in directory:"target"
query = "delete from " + tablemysql + " where name='" + name + "'";
Mysql();
}
}
So when I debug it, it does run through the File.Delete (target + e.Name); but it doesn't delete the file in the second directory. The delete query is working in mysql.
At the top I defined the variable target:
String target = ConfigurationManager.AppSettings[#"Directory2"];
and in the app config:
<add key="Directory2" value="C:\Users\Loko\Desktop\Loko\3"/>
Now I dont see any difference in executing everything in the created event and the deleted event
It has to delete a file in the 2nd directory(target) when the deleted event is called.
To compare some stuff, this is my Created event which works fine:
private void fileSystemWatcher1_Created(object sender, FileSystemEventArgs e)
{
if (!pause)
{
filepath = Path.Combine(source, e.Name);
name = Path.GetFileNameWithoutExtension(filepath);
extension = Path.GetExtension(e.FullPath);
size = e.Name.Length;
readquery = "select * from " + tablemysql + " where name='" + name + "'";
Record();
query = "INSERT INTO " + tablemysql +
" (name,size,last_edit,extension) VALUES('" +
name + "','" + size + "',now(),'" + extension + "')";
Mysql();
if (Directory.Exists(e.FullPath))
{
copyfolder();
Directory.CreateDirectory(target);
}
else
{
if (WaitForFileAvailable(e.FullPath, TimeSpan.FromSeconds(30)))
{
var file = Path.Combine(source, e.Name);
var copy_file = Path.Combine(target, e.Name);
var destination = Path.Combine(target,
Path.ChangeExtension(source, Path.GetExtension(source)));
if (File.Exists(file))// Check to see if the file exists.
{
// If it does delete the file in the target and
// copy the one from the source to the target.
File.Delete(copy_file);
}
File.Copy(e.FullPath, copy_file);
}
}
}
}
What is going wrong here?
You state that your target is defined as "C:\Users\Loko\Desktop\Loko\3". Assuming your filename is "myfile.txt" (for example), then the line:
File.Delete (target + e.Name);
will be attempting to delete "C:\Users\Loko\Desktop\Loko\3myfile.txt", which is missing a path separator.
You should instead use Path.Combine.
File.Delete(Path.Combine(target, e.Name))
Remarks
You may have been expecting an exception to be thrown on the File.Delete call if the file does not exist. However, the documentation states:
If the file to be deleted does not exist, no exception is thrown.
Related
So I have a bit complicated one, I'm trying to create a "template creator". User will input data via comboboxes and textboxes into a form, from which a button generates the names (combination of inputs). After that next button creates directories as required. Until this point everything is ok, however, after this, I prompted a question whether the user wants to start copying files to the newly created directories.
Current code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using Microsoft.VisualBasic;
namespace ME_Nitra_BIW_App
{
public partial class ToolingDesign : Form
{
// create folder path to enable new folder creation
private void btnGenerateFilePath_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
tBoxFilePath.Text = folderBrowserDialog1.SelectedPath;
btnCreateDir.Enabled = true;
}
private void btnCreateDir_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(tBoxFilePath.Text))
{
System.Windows.Forms.MessageBox.Show("No file path selected!");
}
else
{
// for Assembly folder
string fileNameAssy = "FIXED_PARTS_PRODUCT.CATProduct";
string sourcePathAssy = #"c:\Users\mjanus\Downloads\CATIAV5\START_MODELS\CAT_PRODUCTS";
string targetPathAssy = tBoxFilePath.Text + #"\" + tBoxFolderName.Text + #"\" + tBoxFolderName.Text + "_U000" + "_ASSEMBLY";
// use path class to manipulate file and directory paths
string sourceFile = System.IO.Path.Combine(sourcePathAssy, fileNameAssy);
string destFile = System.IO.Path.Combine(targetPathAssy, fileNameAssy);
string dirPath = tBoxFilePath.Text + #"\" + tBoxFolderName.Text + #"\" + tBoxFolderName.Text;
// create new folders with generated names
btnGenerateFilePath.Enabled = false;
btnCreateDir.Enabled = false;
Directory.CreateDirectory(tBoxFilePath.Text + #"\" + tBoxFolderName.Text);
System.Threading.Thread.Sleep(500);
Directory.CreateDirectory(dirPath + "_U000" + "_ASSEMBLY");
Directory.CreateDirectory(dirPath + "_U001" + "_PRODUCT_PARTS");
Directory.CreateDirectory(dirPath + "_U002" + "_CLAMP_STUDY");
Directory.CreateDirectory(dirPath + "_U003" + "_GUN_STUDY");
Directory.CreateDirectory(dirPath + "_U004" + "_PRODUCT_PARTS");
Directory.CreateDirectory(dirPath + "_U005" + "_MECHANICAL_SEQUENCES");
Directory.CreateDirectory(dirPath + "_U006" + "_MISCELLANEOUS");
Directory.CreateDirectory(dirPath + "_U007" + "_SUPPORT");
// ask if user wants to copy template files to the newly created folders
DialogResult dialogResult = MessageBox.Show("Directories successfuly created!" + Environment.NewLine + "Do you wish to copy files now?", "Success!", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
// if the directory folder already exists, this method does not create a new directory
System.IO.Directory.CreateDirectory(targetPathAssy);
// overwrite the destination file if it already exists
System.IO.File.Copy(sourceFile, destFile, true);
// start of copy
if (System.IO.Directory.Exists(sourcePathAssy))
{
string[] files = System.IO.Directory.GetFiles(sourcePathAssy);
foreach (string s in files)
{
fileNameAssy = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPathAssy, fileNameAssy);
System.IO.File.Copy(s, destFile, true);
}
}
else
{
MessageBox.Show("Source path does not exist!");
}
}
else if (dialogResult == DialogResult.No)
{
this.Close();
}
}
}
}
As you can see I've set the targetPathAssy to the same location as what the new folder is created, but I'm not sure if the code can read that? Or how could I store that newly created directory path and call it?
I found the solution, and it's much simpler than what I've tried before.
Here's the full code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using Microsoft.VisualBasic;
namespace ME_Nitra_BIW_App
{
public partial class ToolingDesign : Form
{
public ToolingDesign()
{
InitializeComponent();
radioButton1.CheckedChanged += new EventHandler(radioButton_CheckedChanged);
radioButton2.CheckedChanged += new EventHandler(radioButton_CheckedChanged);
}
private void btnCreateDir_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(tBoxFilePath.Text))
{
System.Windows.Forms.MessageBox.Show("No file path selected!");
}
else
{
// directory path
string dirPath = tBoxFilePath.Text + #"\" + tBoxFolderName.Text + #"\" + tBoxFolderName.Text;
// where to paste the files
string targetPathAssy = dirPath + "_U000" + "_ASSEMBLY";
// create new folders with generated names
btnGenerateFilePath.Enabled = false;
btnCreateDir.Enabled = false;
Directory.CreateDirectory(tBoxFilePath.Text + #"\" + tBoxFolderName.Text);
System.Threading.Thread.Sleep(500);
Directory.CreateDirectory(dirPath + "_U000" + "_ASSEMBLY");
Directory.CreateDirectory(dirPath + "_U001" + "_PRODUCT_PARTS");
Directory.CreateDirectory(dirPath + "_U002" + "_CLAMP_STUDY");
Directory.CreateDirectory(dirPath + "_U003" + "_GUN_STUDY");
Directory.CreateDirectory(dirPath + "_U004" + "_PRODUCT_PARTS");
Directory.CreateDirectory(dirPath + "_U005" + "_MECHANICAL_SEQUENCES");
Directory.CreateDirectory(dirPath + "_U006" + "_MISCELLANEOUS");
Directory.CreateDirectory(dirPath + "_U007" + "_SUPPORT");
// ask if user wants to copy template files to the newly created folders
DialogResult dialogResult = MessageBox.Show("Directories successfuly created!" + Environment.NewLine + "Do you wish to copy files now?", "Success!", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
// test copy
File.Copy(#"Resources\UNIT_START_PRODUCT.CATProduct", targetPathAssy + #"\" + "UNIT_START_PRODUCT.CATProduct");
}
else if (dialogResult == DialogResult.No)
{
this.Close();
}
}
}
// create folder path to enable new folder creation
private void btnGenerateFilePath_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
tBoxFilePath.Text = folderBrowserDialog1.SelectedPath;
btnCreateDir.Enabled = true;
}
}
}
The change:
Turns out that I can use the same string to copy the file to the newly created directory which uses the string dirPath as shown above. Although I've embedded the files into the application (ease of use, not sure if I would get a dedicated folder on the server) I've used the
File.Copy(#"Resources\UNIT_START_PRODUCT.CATProduct", targetPathAssy + #"\" + "UNIT_START_PRODUCT.CATProduct");
I had to add the #"\" because otherwise the copied file would have the targetPathAssy added to its name instead of going into the specific folder.
Hope this helps someone in the future
I have some c# code and recently I added a button to the form designer which runs a simple update table query (update a SQL table). The table is updated as I would expect when I manually click the button in Debug mode, however when I run the entire program, it appears the method/button to update the SQL table is either ignored or simply not being picked up. As I mentioned, this works fine when I go into Debug and click on the button manually, however what I need it to do is run the method and click the button automatically as it is doing for the other methods. I have gone through this hundreds of times and am at the end of the road. Below is my code;
private void updateClosedModuleState()
{
System.Data.SqlClient.SqlConnection saConn = new System.Data.SqlClient.SqlConnection();
saConn.ConnectionString = GlobalDef.strSQLConnection;
//MessageBox.Show(saConn.ConnectionString);
try
{
saConn.Open();
SqlCommand command = saConn.CreateCommand();
command.CommandTimeout = saConn.ConnectionTimeout;
command.CommandType = System.Data.CommandType.Text;
command.CommandText = " UPDATE SATA_AllocationObject "
+ " SET State = REPLACE(State, 'A', 'I') "
+ " where AllocationObjectType = 4 "
+ " and Hostkey in (select hostkey from TRAN_UnitEClosedModules)";
command.ExecuteNonQuery();
}
catch (Exception act)
{
MessageBox.Show("Ooops! Error " + act.Message.ToString() + " when updating Module State");
}
finally
{
saConn.Close();
}
pictureBox19.Visible = true;
}
This is the code for the button click;
private void cmdUpdateClosedModuleState_Click(object sender, EventArgs e)
{
updateClosedModuleState();
}
Lastly, these are the method details in the form designer;
this.cmdUpdateClosedModuleState.Location = new System.Drawing.Point(517, 114);
this.cmdUpdateClosedModuleState.Name = "cmdUpdateClosedModuleState";
this.cmdUpdateClosedModuleState.Size = new System.Drawing.Size(107, 23);
this.cmdUpdateClosedModuleState.TabIndex = 41;
this.cmdUpdateClosedModuleState.Text = "UpdateModState";
this.cmdUpdateClosedModuleState.UseVisualStyleBackColor = true;
this.cmdUpdateClosedModuleState.Click += new System.EventHandler(this.cmdUpdateClosedModuleState_Click);
I have also tried to use a TableAdapter and use a Fill to update the SQL Table via the button, and that works...only when I click the button in Debug mode;
private void newupdate()
{
//throw new NotImplementedException();
this.sATA_AllocationObject1TableAdapter.Fill(this.moduleSignupTestDataSet.SATA_AllocationObject1);
}
I assigned a buttton to run the Fill on the TableAdapter;
private void newupdate_Click(object sender, EventArgs e)
{
//this.sATA_AllocationObject1TableAdapter.Fill(this.moduleSignupTestDataSet.SATA_AllocationObject1);
newupdate();
}
So in a nutshell, I need the program to run this method like it does with all the other ones without my intervention.
I have attached a photo of the form - when I click 'Run All' everything runs except for the UpdateClosedModState; [1]: https://i.stack.imgur.com/dJryA.png
The code behind the Run All command is;
private void cmdRunAll_Click(object sender, EventArgs e)
{
begin();
}
In the form designer we have;
this.cmdRunAll.Location = new System.Drawing.Point(381, 375);
this.cmdRunAll.Name = "cmdRunAll";
this.cmdRunAll.Size = new System.Drawing.Size(107, 21);
this.cmdRunAll.TabIndex = 10;
this.cmdRunAll.Text = "Run All";
this.cmdRunAll.UseVisualStyleBackColor = true;
this.cmdRunAll.Click += new System.EventHandler(this.cmdRunAll_Click);
And at the start of the form, we have this to begin running the app;
if (args.Length > 0)
{
lArgsExists = true;
// strDetails = strDetails + ": About to run app.";
// runApp(args[0], lArgsExists);
begin();
}
}
public void runApp(string cnfgPath, bool gui)
{
if (gui == true)
{
strDetails = strDetails + " Running app.";
begin();
}
else
{
textBox2.Text = GlobalDef.appStatus.ToString();
begin();
//MessageBox.Show("Opening form!");
}
}
public void begin()
{
String sqlServerLogin = GlobalDef.sqlServerlogin;
String password = GlobalDef.password;
String instanceName = GlobalDef.instanceName;
String remoteSvrName = GlobalDef.remoteSvrName;
string strNow = DateTime.Now.Day + "/" + DateTime.Now.Month + "/" + DateTime.Now.Year;
string strSQLConnection = GlobalDef.strSQLConnection;
textBox2.Text = GlobalDef.appStatus.ToString();
//string path = #"E:\Allocator\StudentAllocatorTest\logs\Error.log";
string path = GlobalDef.path;
// This text is added only once to the file.
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Error details");
}
}
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine();
sw.WriteLine("******************************************");
sw.WriteLine();
sw.WriteLine(strDetails.ToString());
sw.WriteLine("******************************************");
sw.WriteLine();
sw.WriteLine(DateTime.Now.ToString() + ": Starting load for " + GlobalDef.instanceName);
}
try
{
string connString = GlobalDef.connString;
OracleConnection oraCon = new OracleConnection(connString);
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
conn.ConnectionString =
"data source=" + remoteSvrName + ";" +
"persist security info=true;initial catalog=" + instanceName + ";User Id=" + sqlServerLogin + "; Password=" + password + ";";
// Clear transfer tables before running any subroutine
clearTransTables();
// Loads Department details into SA TransTables
updateDepartment(oraCon, strSQLConnection);
// Loads new POSA modules into SA TransTables
updatePOSA(oraCon, strSQLConnection, path);
// Loads new POSY modules into SA TransTables
updatePOSY(oraCon, strSQLConnection, path);
// Remove open option links for modules which do not have the timetable flag checked
RemoveUnneededOOCourses(oraCon, strSQLConnection, path);
// Loads top-level OO structure into SA TransTables
OpenOption(oraCon, strSQLConnection, path);
// Loads Dept level OO structure into SA TransTables
OptionByDept(oraCon, strSQLConnection, path);
// Links OOByDept Allocation Objects to OO Objects via TransTables
linkOOAndOOByDept(path);
// Loads new Course modules into SA TransTables
updateCourse(oraCon, strSQLConnection, path);
// Links OO courses to OOByDept AllocationObjects via TransTables
OpenOptionCourses(oraCon, strSQLConnection, path);
//Adds All Courses to various hidden groups via TransTables
updateAllHidden(oraCon, strSQLConnection, path);
// Loads new students into SA TransTables
//TransferStudent(oraCon, strSQLConnection);
// Loads prerequisite allocations into SA TransTables
UploadPrerequisites(oraCon, strSQLConnection);
//button1_Click();
// Loads Closed Modules from UnitE to TRAN_UnitEClosedModules
uploadUnitEClosedModules(oraCon, strSQLConnection);
//Runs the transfer service which loads the data in the TransTables into the database
runTransferservice(path);
///
newupdate();
// update Closed Modules to 'I' State
updateClosedModuleState();
// Used to create a structure for programmes which had yet to be set up by faculties
// DefaultCourseStructure(oraCon, strSQLConnection);
// Creates UNITe course enrolments and cancels changed course selections
uploadAllocationsToUNITe(oraCon, strSQLConnection, path);
// pictureBox11.Visible = true;
}
catch (Exception e)
{
MessageBox.Show(e.Message.ToString());
}
finally
{
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine(DateTime.Now.ToString() + ": Completed load for " + GlobalDef.instanceName);
}
Application.Exit();
}
}
private void updateDepartment(OracleConnection oraCon, string strSQLConnection)
{
try
{
....and it goes on with the subroutines listed above.
Any help would be greatly appreciated.
Thank you in advance.
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.
}
private void Recorder_ExecuteCode(object sender, EventArgs e)
{
fileName = "";
SendMail = false;
CallIsAlive = true;
Recorder recorder = new Recorder();
// Use the call ID as the filename and create a media sink.
Random rnd = new Random();
fileName = string.Format("C:\\recordings\\Inbound Call\\EmergencyCall {0}.wma", DateTime.Now.Day.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Year.ToString() + " - " + DateTime.Now.Hour.ToString() + "." + DateTime.Now.Minute.ToString() + "." + DateTime.Now.Second.ToString() + rnd.Next().ToString());
WmaFileSink fileSink = new WmaFileSink(fileName);
Console.WriteLine("Recording for 10 seconds.");
// Set the recorder to use the media sink and attach
// it to the flow.
recorder.SetSink(fileSink);
recorder.AttachFlow(Program.MyCall.Flow);
// Start recording.
recorder.Start();
SendMail = true;
}
The above piece of code sets up a recorder that attaches to the audiovideoflow of the inbound call.
The issue im having is that if 2 calls come in at the same time and try and call the Recorder_executeCode function, the program crashes here:
recorder.AttachFlow(Program.MyCall.Flow);
Visual Studio reports the following error:
InvalidOperationException was unhandled by user code.
AudioVideoFlow is already bound to a Recorder.
How would I go about changing the code to allow more than one copy of the function to run at the same time if two or more callers call in at the same time.
Edit
The issue was being caused by using the global variable: MyCall
I fixed the issue by setting the filename string using the Call.CallId
private void Recorder_ExecuteCode(object sender, EventArgs e)
{
string fileName;
SendMail = false;
Recorder recorder = new Recorder();
// Use the call ID as the filename and create a media sink.
//Random rnd = new Random();
fileName = string.Format("C:\\recordings\\Inbound Call\\EmergencyCall {0}.wma", acceptCallActivityInboundCall1.CallProvider.ToneController.AudioVideoFlow.Call.CallId.ToString());
WmaFileSink fileSink = new WmaFileSink(fileName);
Console.WriteLine("Recording for 10 seconds.");
// Set the recorder to use the media sink and attach
// it to the flow.
recorder.SetSink(fileSink);
recorder.AttachFlow(acceptCallActivityInboundCall1.CallProvider.ToneController.AudioVideoFlow);
// Start recording.
recorder.Start();
SendMail = true;
}
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);
}