SaveFileDialog Menuclick Item Doesnt Work. - c#

If I set path = "C:\\MSREAD.txt"; and Click on SaveAs Menu Item ,it saves Filetext,But If I dont give the String path and save it from saveFD.FileName it doesnt work.Please help me with this issue.
Thanks a lot
public void SaveToFile()
{
String SavedFile = "";
saveFD.InitialDirectory = #"C:";
saveFD.Title = "Save a Text File";
saveFD.FileName = "";
RichTextBox richTextBox1 = new RichTextBox();
saveFD.Filter = "Text Files|*.txt|All Files|*.*";
try
{
if (saveFD.ShowDialog() != DialogResult.Cancel)
{
SavedFile = saveFD.FileName;
path = SavedFile.ToString();
//path = "C:\\MSREAD.txt";
MessageBox.Show(path);
richTextBox1.SaveFile(path, RichTextBoxStreamType.PlainText);
SaveMyTextBoxContents(path);
}
}
catch(Exception e)
{
MessageBox.Show(e.ToString());
}
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveToFile();
}
public void SaveMyTextBoxContents(string path)
{
if (listBoxItems.SelectedIndex == -1)
{
if (rdBtnSlow.Checked && rdBtnNo.Checked)
{
using (StreamWriter outputFile = new StreamWriter(path))
{
foreach (string item in listBoxItems.Items)
{
saveAllText = slowNo + " " + item;
outputFile.WriteLine(saveAllText);
}
}
}
}
}

Here is your problem:
richTextBox1.SaveFile(path, RichTextBoxStreamType.PlainText);
SaveMyTextBoxContents(path);
You first save the richTextBox text to file, but then override the same file with SaveMyTextBoxContents, However the file is empty because of SaveMyTextBoxContents method will only save something if some conditions are true "not selected item and both check boxes are checked", and the listBoxItems.Items.Count > 0 which apparently not the case

Related

How to check if text file is already added or opened

I would like to open and add a text file content into a list Box, but if I want to add another text file, how do I check if the file that I add is already added into the list Box. I mean I don't want the list box to be duplicated.
private void openAndAddToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog.Filter = "Text file|*.txt";
openFileDialog.Title = "Open Text";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
List<string> lines = new List<string>();
using (StreamReader r = new StreamReader(openFileDialog.OpenFile()))
{
string line;
while ((line = r.ReadLine()) != null)
{
donutListBox.Items.Add(line);
}
}
}
}
Add an if:
if ( !donutListBox.Items.Contains(line) ){
donutListBox.Items.Add(line);
}
If you on .net framework 4+, you can use File.ReadAllLines(string filename) static method:
private void openAndAddToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog.Filter = "Text file|*.txt";
openFileDialog.Title = "Open Text";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
var lines = File.ReadAllLines(openFileDialog.FileName);
lines = lines.Where(line => !donutListBox.Items.Contains(line)).ToArray();
donutListBox.Items.AddRange(lines);
}
}
You can try is
public static bool IsFileInUse(string filename)
{
bool locked = false;
try
{
FileStream fs =
File.Open(filename, FileMode.OpenOrCreate,
FileAccess.ReadWrite, FileShare.None);
fs.Close();
}
catch (IOException ex)
{
locked = true;
}
return locked;
}
And :
if(!Class.IsFileInUse("FilePAth") && !donutListBox.Items.Contains(line))
{
//your code
}

Only ask for filename if one has not been input

I am using C# and a winform and am saving data to a .xlsx on a button click event. I have a unique situation that I am not sure how to code for....
If the form is still displayed and the user clicks the button, I want it to prompt for a file name and save location. BUT if the form has not been closed and the user clicks the button a second time, I want .xlsx to be saved in the same location and with the same filename and over write with no prompt.
This is the syntax I use to prompt for save name and location, but how do I check to determine if a filename/save location has already been input and if it has do not prompt again?
private void btnOne_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.InitialDirectory = #"C:\";
save.RestoreDirectory = true;
save.Title = "Select save location file name";
save.DefaultExt = "xlsx";
if (save.ShowDialog() == DialogResult.OK)
{
try
{
var file = new FileInfo(save.FileName);
using (var package = new ExcelPackage(file))
{
package.Save();
}
}
catch { Messagebox.Show("An error has occured"; }
}
}
So, whether the data has a set filename is a part of the state of the class. Inside the class where you have btnOne_Click, just define a string with the filename, defaulted to null:
string filepath = null;
Then, in your btnOne_Click, you want to check for the filepath. If it's not there, open the saveAs dialog. After that, if filepath is set, just save. It will be restructured like this:
private void btnOne_Click(object sender, EventArgs e)
{
if (filepath == null)
{
SaveFileDialog save = new SaveFileDialog();
save.InitialDirectory = #"C:\";
save.RestoreDirectory = true;
save.Title = "Select save location file name";
save.DefaultExt = "xlsx";
if (save.ShowDialog() == DialogResult.OK) {
filepath = save.FileName;
}
}
if (filepath != null)
{
try
{
var file = new FileInfo(filepath);
using (var package = new ExcelPackage(file))
{
package.Save();
}
}
catch { MessageBox.Show("An error has occured"; }
}
}
This logical structure gives you standard behavior for when a user presses a save button. If they cancel the saveAs dialog, then the save is aborted and the filename state is not changed.
Declare this globally:
public string Filename;
Then change your subroutine like this:
private void btnOne_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(Filename))
{
SaveFileDialog save = new SaveFileDialog();
save.InitialDirectory = #"C:\";
save.RestoreDirectory = true;
save.Title = "Select save location file name";
save.DefaultExt = "xlsx";
if (save.ShowDialog() == DialogResult.OK)
{
try
{
Filename = save.FileName;
var file = new FileInfo(save.FileName);
using (var package = new ExcelPackage(file))
{
package.Save();
}
}
catch { MessageBox.Show("An error has occured"); }
}
}
else
{
var file = new FileInfo(Filename);
using (var package = new ExcelPackage(file))
{
package.Save();
}
}
}

How to save filename only to the gridview but I need path while downloading the file

I got finally, how to download the file using the path. But I was wondering how can I keep the file name only on the grid view. While I need the full path for downloading.
On debugging I came to see that I cannot keep file name only on file upload. Since it is carried to the downloading section. If I keep file name, then file name is carried to the downloading part and the file is not downloaded.
Can anyone help me
Codes
private void UploadAttachment(DataGridViewCell dgvCell)
{
using (OpenFileDialog fileDialog = new OpenFileDialog())
{
//Set File dialog properties
fileDialog.CheckFileExists = true;
fileDialog.CheckPathExists = true;
fileDialog.Filter = "All Files|*.*";
fileDialog.Title = "Select a file";
fileDialog.Multiselect = true;
if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string strfilename = fileDialog.FileName;
cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value = strfilename;
}
}
}
/// <summary>
/// Download Attachment from the provided DataGridViewCell
/// </summary>
/// <param name="dgvCell"></param>
private void DownloadAttachment(DataGridViewCell dgvCell)
{
string fileName = Convert.ToString(dgvCell.Value);
if (!string.IsNullOrEmpty(fileName))
{
byte[] objData;
FileInfo fileInfo = new FileInfo(fileName);
string fileExtension = fileInfo.Extension;
//show save as dialog
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
{
//Set Save dialog properties
saveFileDialog1.Filter = "Files (*" + fileExtension + ")|*" + fileExtension;
saveFileDialog1.Title = "Save File as";
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.FileName = fileName;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string s = cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value.ToString();
objData = File.ReadAllBytes(s);
File.WriteAllBytes(saveFileDialog1.FileName, objData);
}
}
}
}
}
Your question is not clear. But if i get you right. Why don't you use use a column for the name and a hidden/0 width column for the file path. Its a grid and therefore you may have many columns. Plus i am thinking the code below should return the full path , unless you trim and can't see where you trim .
string strfilename = fileDialog.FileName;
To get the file name only you can use the Path
string filenameOnly= System.IO.Path.GetFileName(strfilename);
The above should return your file name only you can check here for better understanding.
Add another column and set the width to 0 . Example below
DataGridViewColumn column = dataGridView.Columns[0];
column.Width = 0;
cncInfoDataGridView.Columns.Add(column);
Save your file path in the new column width a 0 width and retrieve during download.
A similar question was asked here.
How to extract file name from file path name?
Dictionary<int, byte[]> _myAttachments;
private void btnUpload_Click(object sender, EventArgs e)
{
try
{
//Throw error if attachment cell is not selected.
//make sure user select only single cell
if (dataGridView1.SelectedCells.Count == 1 && dataGridView1.SelectedCells[0].ColumnIndex == 1)
{
UploadAttachment(dataGridView1.SelectedCells[0]);
}
else
MessageBox.Show("Select a single cell from Attachment column", "Error uploading file", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error uploading file", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnDownload_Click(object sender, EventArgs e)
{
//Throw error if attachment cell is not selected.
//make sure user select only single cell
//and the cell have a value in it
if (dataGridView1.SelectedCells.Count == 1 && dataGridView1.SelectedCells[0].ColumnIndex == 1 && dataGridView1.SelectedCells[0].Value != null)
{
DownloadAttachment(dataGridView1.SelectedCells[0]);
}
else
MessageBox.Show("Select a single cell from Attachment column", "Error uploading file", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
//Throw error if attachment cell is not selected.
//make sure user select only single cell
//and the cell have a value in it
if (dataGridView1.SelectedCells.Count == 1 && dataGridView1.SelectedCells[0].ColumnIndex == 1 && dataGridView1.SelectedCells[0].Value != null)
{
DownloadAttachment(dataGridView1.SelectedCells[0]);
}
else
MessageBox.Show("Select a single cell from Attachment column", "Error uploading file", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void UploadAttachment(DataGridViewCell dgvCell)
{
using (OpenFileDialog fileDialog = new OpenFileDialog())
{
//Set File dialog properties
fileDialog.CheckFileExists = true;
fileDialog.CheckPathExists = true;
fileDialog.Filter = "All Files|*.*";
fileDialog.Title = "Select a file";
fileDialog.Multiselect = false;
if (fileDialog.ShowDialog() == DialogResult.OK)
{
FileInfo fileInfo = new FileInfo(fileDialog.FileName);
byte[] binaryData = File.ReadAllBytes(fileDialog.FileName);
dataGridView1.Rows[dgvCell.RowIndex].Cells[1].Value = fileInfo.Name;
if (_myAttachments.ContainsKey(dgvCell.RowIndex))
_myAttachments[dgvCell.RowIndex] = binaryData;
else
_myAttachments.Add(dgvCell.RowIndex, binaryData);
}
}
}
private void DownloadAttachment(DataGridViewCell dgvCell)
{
string fileName = Convert.ToString(dgvCell.Value);
//Return if the cell is empty
if (fileName == string.Empty)
return;
FileInfo fileInfo = new FileInfo(fileName);
string fileExtension = fileInfo.Extension;
byte[] byteData = null;
//show save as dialog
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
{
//Set Save dialog properties
saveFileDialog1.Filter = "Files (*" + fileExtension + ")|*" + fileExtension;
saveFileDialog1.Title = "Save File as";
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.FileName = fileName;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
byteData = _myAttachments[dgvCell.RowIndex];
File.WriteAllBytes(saveFileDialog1.FileName, byteData);
}
}
}

Proper functioning of 'Save file' in Notepad program in C#

public partial class Form1 : Form
{
SaveFileDialog sfd = new SaveFileDialog();
OpenFileDialog ofd = new OpenFileDialog();
public string contents = string.Empty;
public Form1()
{
InitializeComponent();
this.Text = "Untitled";
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
if (richTextBox1.Text != contents)
{
DialogResult dr = MessageBox.Show("Do You want to save the changes made to " + this.Text, "Save", MessageBoxButtons.YesNoCancel);
if (dr == DialogResult.Yes)
{
sfd.Title = "Save";
if (SaveFile() == 0)
return;
else
{
richTextBox1.Text = "";
this.Text = "Untitled";
}
contents = "";
}
else if (dr == DialogResult.No)
{
richTextBox1.Text = "";
this.Text = "Untitled";
contents = "";
}
else
{
richTextBox1.Focus();
}
}
else
{
this.Text = "Untitled";
richTextBox1.Text = "";
contents = "";
}
}
private int SaveFile()
{
sfd.Filter = "Text Documents|*.txt";
sfd.DefaultExt = "txt";
if (sfd.ShowDialog() == DialogResult.Cancel)
{
richTextBox1.Focus();
return 0;
}
else
{
contents = richTextBox1.Text;
if (this.Text == "Untitled")
richTextBox1.SaveFile(sfd.FileName,RichTextBoxStreamType.PlainText);
else
{
sfd.FileName = this.Text;
richTextBox1.SaveFile(sfd.FileName,RichTextBoxStreamType.PlainText);
}
this.Text = sfd.FileName;
return 1;
}
}
private void OpenFile()
{
ofd.Filter = "Text Documents|*.txt";
if (ofd.ShowDialog() == DialogResult.Cancel)
richTextBox1.Focus();
else
{
richTextBox1.LoadFile(ofd.FileName, RichTextBoxStreamType.PlainText);
this.Text = ofd.FileName;
contents = richTextBox1.Text;
}
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if (richTextBox1.Text != contents)
{
DialogResult dr = MessageBox.Show("Do You want to save the changes made to " + this.Text, "Save", MessageBoxButtons.YesNoCancel);
if (dr == DialogResult.Yes)
{
SaveFile();
OpenFile();
}
else if (dr == DialogResult.No)
{
OpenFile();
}
else
{
richTextBox1.Focus();
}
}
else
OpenFile();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFile();
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
sfd.Filter = "Text Documents|*.txt";
sfd.DefaultExt = "txt";
if (sfd.ShowDialog() == DialogResult.Cancel)
{
richTextBox1.Focus();
}
else
{
contents = richTextBox1.Text;
richTextBox1.SaveFile(sfd.FileName, RichTextBoxStreamType.PlainText);
this.Text = sfd.FileName;
}
}
When we open Windows notepad application then open a file, changes it contents and save it, it simply gets saved without opening the Save File dialog. But in the notepad program I have created above the Save File dialog opens on clicking 'Save' after changing the contents of saved file. Although the same file name appears in the save file dialog but on clicking 'Save' it gives a message "The same file name already exists. Do you want to replace it?". That is what I want to remove and make the changed contents saved directly to the opened file without opening the save file dialog.
Set sfd.OverwritePrompt = false any time after construction and before ShowDialog to suppress the overwrite warning.
You want to have two choices to save: A 'Save As..' button and a 'Save' button. You can create a string to hold the path of the opened file. The location may also change if the user specifies a new location when they save the file. If the user did not open the file, the 'Save As...' button would open the regular Save File Dialog. Once the user specifies the location of their document, you can save the file path to that string and use a `StreamWriter' to save it without the dialog:
...
using System.IO;
...
public partial class Form1 : Form
{
SaveFileDialog sfd = new SaveFileDialog();
OpenFileDialog ofd = new OpenFileDialog();
public string contents = string.Empty;
//string to hold file location
string currentFileLoc;
public Form1()
{
InitializeComponent();
this.Text = "Untitled";
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
if (richTextBox1.Text != contents)
{
DialogResult dr = MessageBox.Show("Do You want to save the changes made to " + this.Text, "Save", MessageBoxButtons.YesNoCancel);
if (dr == DialogResult.Yes)
{
sfd.Title = "Save";
if (SaveFile() == 0)
return;
else
{
richTextBox1.Text = "";
this.Text = "Untitled";
}
contents = "";
}
else if (dr == DialogResult.No)
{
richTextBox1.Text = "";
this.Text = "Untitled";
contents = "";
}
else
{
richTextBox1.Focus();
}
}
else
{
this.Text = "Untitled";
richTextBox1.Text = "";
contents = "";
}
}
private int SaveFile()
{
sfd.Filter = "Text Documents|*.txt";
sfd.DefaultExt = "txt";
if (sfd.ShowDialog() == DialogResult.Cancel)
{
richTextBox1.Focus();
return 0;
}
else
{
contents = richTextBox1.Text;
if (this.Text == "Untitled")
richTextBox1.SaveFile(sfd.FileName,RichTextBoxStreamType.PlainText);
else
{
sfd.FileName = this.Text;
richTextBox1.SaveFile(sfd.FileName,RichTextBoxStreamType.PlainText);
}
this.Text = sfd.FileName;
//
currentFileLoc = sfd.FileName;
return 1;
}
}
private void OpenFile()
{
ofd.Filter = "Text Documents|*.txt";
if (ofd.ShowDialog() == DialogResult.Cancel)
richTextBox1.Focus();
else
{
richTextBox1.LoadFile(ofd.FileName, RichTextBoxStreamType.PlainText);
this.Text = ofd.FileName;
contents = richTextBox1.Text;
}
currentFileLoc = ofd.FileName;
this.Text = currentFileLoc;
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if (richTextBox1.Text != contents)
{
DialogResult dr = MessageBox.Show("Do You want to save the changes made to " + this.Text, "Save", MessageBoxButtons.YesNoCancel);
if (dr == DialogResult.Yes)
{
SaveFile();
OpenFile();
}
else if (dr == DialogResult.No)
{
OpenFile();
}
else
{
richTextBox1.Focus();
}
}
else
OpenFile();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
Save();
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFile();
}
//new method
private void Save()
{
if (currentFileLoc != null)
{
using (StreamWriter writer = new StreamWriter(currentFileLoc))
{
writer.WriteLine(richTextBox1.Text);
}
}
else
saveFile();
}
}
I suggest you also enclose the using(...){ } block in a try/catch statement and handle any exceptions.
What you need to do is save the filename entered, then, when the save option is pressed, check for a previously entered filename. If you have one, skip showing the dialog and just execute the save code.

how to remember the last path when insert files into Listbox

i have application with Listbox and files, each time i press on Add button the default C drive open and i want the application to remember the last path i used
private void btnAdd_Click(object sender, EventArgs e)
{
System.IO.Stream myStream;
OpenFileDialog thisDialog = new OpenFileDialog();
thisDialog.InitialDirectory = "c:\\";
thisDialog.Filter = "(*.snoop, *.pcap, *.cap, *.net)|*.snoop; *.pcap; *.cap; *.net|" + "All files (*.*)|*.*";
thisDialog.FilterIndex = 1;
thisDialog.RestoreDirectory = false;
thisDialog.Multiselect = true; // Allow the user to select multiple files
thisDialog.Title = "Please Select Source File";
thisDialog.FileName = lastPath;
List<string> list = new List<string>();
if (thisDialog.ShowDialog() == DialogResult.OK)
{
foreach (String file in thisDialog.FileNames)
{
try
{
if ((myStream = thisDialog.OpenFile()) != null)
{
using (myStream)
{
listBoxFiles.Items.Add(file);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
}
Save the last directory used in a global variable like this:
private string _lastPath = string.Empty;
then after the file selection initialize it:
if(thisDialog.Filenames.Length > 0)
_lastPath = Path.GetDirectoryName(thisDialog.Filenames[0]);
when you reopen the dialog set the InitialDirectory with this check:
thisDialog.InitialDirectory = (_lastPath.Length > 0 ? _lastPath: "c:\\");
and remove the thisDialog.FileName = lastPath;
EDIT --- UPDATE OF YOUR CODE ---
// This at the global level of your form
private string _lastPath = string.Empty;**
private void btnAdd_Click(object sender, EventArgs e)
{
System.IO.Stream myStream;
OpenFileDialog thisDialog = new OpenFileDialog();
thisDialog.InitialDirectory = (_lastPath.Length > 0 ? _lastPath: "c:\\");
thisDialog.Filter = "(*.snoop, *.pcap, *.cap, *.net)|*.snoop; *.pcap; *.cap; *.net|" + "All files (*.*)|*.*";
thisDialog.FilterIndex = 1;
thisDialog.RestoreDirectory = false;
thisDialog.Multiselect = true; // Allow the user to select multiple files
thisDialog.Title = "Please Select Source File";
thisDialog.FileName = lastPath;
List<string> list = new List<string>();
if (thisDialog.ShowDialog() == DialogResult.OK)
{
if(thisDialog.Filenames.Length > 0)
_lastPath = Path.GetDirectoryName(thisDialog.Filenames[0]);
foreach (String file in thisDialog.FileNames)
{
try
{
if ((myStream = thisDialog.OpenFile()) != null)
{
using (myStream)
{
listBoxFiles.Items.Add(file);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
}
You can use a Visual Studio have the last path value for every execution of the application.
Only have to go to Project Properties->Configuration and add a value descriptor.
Example:
Name = LastPath; Type = string; Scope = User; Value = "Default path";
And then after you rebuild yout application, you can set this property this way:
Settings.Default.LastPath = LastPathSelected;
later, you can retrieve the value with:
thisDialog.InitialDirectory = Settings.Default.LastPath;
thisDialog.InitialDirectory = Path.GetDirectoryName(lastPath);
Yes, you can use the OpenFileDialog.InitialDirectory property. Note: you are setting the directory and not the file. So be sure to remove the filename from the path.
more info here
remove this line and you have the last path
thisDialog.InitialDirectory = "c:\\";

Categories