Saving a currently opened file without prompts - c#

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);
}

Related

Copy file to newly created directories

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

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.
}

Application still says file is open and display error

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);

Why does my SaveFileDialog display again if cancelled?

I have a SaveFileDialog in my program. The issue is that when I click "Cancel" on the dialog, another SaveFileDialog opens up. But when I click cancel on the second SaveFileDialog, a third does NOT appear, so it's not a loop or anything like that. I can't see what is causing my SaveFileDialog to behave in such an odd manner. Obviously I need to fix this so that if the user clicks cancel on the first SaveFileDialog, it returns them to the form.
The code for saving in my program is as follows:
private void SaveFile()
{
if (filepath == null)
{
SaveFileAs();
}
else
{
StreamWriter sw = new StreamWriter(filepath);
try
{
sw.WriteLine(richTextBoxPrintCtrl1.Rtf);
richTextBoxPrintCtrl1.Modified = false;
sw.Close();
lastsave.Text = "Last Saved: " + DateTime.Now.ToString();
}
catch (Exception exc)
{
MessageBox.Show("Failed to save file. \n \n" + exc.Message);
}
finally
{
if (sw != null) sw.Close();
}
And SaveFileAs
private void SaveFileAs()
{
SaveFileDialog sfdSaveFile = new SaveFileDialog();//Creates a new instance of the SaveFileDialog
sfdSaveFile.Title = "Save File";//The title of the SaveFileDialog window
sfdSaveFile.FileName = "Untitled";//The default filename in the SaveFileDialog window
sfdSaveFile.Filter = "Rich Text Files (*.rtf)|*.rtf|Text Document (*.txt)|*.txt";//The supported file extensions when saving
if (sfdSaveFile.ShowDialog() == DialogResult.OK)//If the condition is correct, run the lines of code
try//try to run the code
{
filepath = sfdSaveFile.FileName;//get the filepath of the file once it is saved
SaveFile();//Calls the SaveFile object
this.Text = string.Format("{0} - Basic Word Processor", Path.GetFileName(sfdSaveFile.FileName));//Set the form name
lastsave.Text = "Last Saved: " + DateTime.Now.ToString();//Writes the text to the lastsave.Text label, followed by the current date and time
richTextBoxPrintCtrl1.Modified = false;
return;
}
catch (Exception exc)//Catches any errors
{
MessageBox.Show("An error occured whilst saving. " + exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (sfdSaveFile.ShowDialog() == DialogResult.Cancel)
{
return;
}
else if (sfdSaveFile.ShowDialog() == DialogResult.Cancel)//If the condition is true, run the line of code
{
return;
}
If anyone could help me determine why this is occurring, I'd really appreciate it..
--EDIT--
I forgot to mention that if the user does go through and save the file, the SaveFileDialog doesn't open up another SaveFileDialog. It is something to do with cancelling the SaveFileDialog which causes the issue.
sfdSaveFile.ShowDialog() opens the file dialog. If it's not DialogResult.OK the first time, it goes to the else clause and gets called again. Store the result of ShowDialog and check what it is, don't call it every time.
In order to do so, use this sort of if/else:
DialogResult dialogResult = sfdSaveFile.ShowDialog();
if (dialogResult == DialogResult.OK)
{
}
else if (dialogResult == DialogResult.Cancel)
{
}

Export directly to pdf

I am using two stored procedures, one for main report and another for subreport. Below is the code.
private void LoadSalesOrderReport()
{
string Type = gvQuotationDetails.Rows[QuoteIndex].Cells["Type"].EditedFormattedValue.ToString();
FilePath = ConfigurationManager.AppSettings["EMP_IMG_PATH"].ToString() + "\\" + ValQuoteID.ToString() + ".pdf";
DeleteExistingFile(FilePath);
try
{
AccountsPayableMaster objAPM = new AccountsPayableMaster();
QuotationReport obj = new QuotationReport();
objReportDocument.Load(Application.StartupPath + #"\rptQuotationReport.rpt");
obj.crysQuotationReport.LogOnInfo = objAPM.ConnectionDetails("SD_SalesOrderReport;1");
obj.crysQuotationReport.LogOnInfo = objAPM.ConnectionDetails("SD_GetBatchReportDetails;1");
obj.crysQuotationReport.ReportSource = objReportDocument;
objReportDocument.SetParameterValue("#QuoteID", ValQuoteID);
objReportDocument.SetParameterValue("Type", "-" + Type.ToUpper() + "-");
objReportDocument.SetParameterValue("#QuoteID", ValQuoteID, objReportDocument.Subreports[0].Name.ToString());
string[] Print = objAPM.GetPrintDetails();
SetPrintParameters(objReportDocument, Print);
obj.Show();
objReportDocument.ExportToDisk(ExportFormatType.PortableDocFormat, FilePath);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
OpenPdfFile();
}
private void OpenPdfFile()
{
try
{
Process.Start(FilePath);
}
catch (Exception ex)
{
MessageBox.Show("Please install MicrosoftOffice/Pdf Reader to view files", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
The code is working fine.But the problem is. when i click the button in front end to show the pdf directly.The crystal report form is also displayed and I know the reason as I am using obj.Show in my code.I tried to comment it but it throws an error.Can any one advise changes in my code to directly display the pdf and not the crystalreport form.

Categories