How to export a listView to a txt file? - c#

I'm starting to program in C# and I want to export the data of a ListView to a txt-file, I have this code, but it does not export the data to the txt-file when I press the button destined for this task.
private void export2File(ListView lv, string splitter)
{
string filename = "";
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "SaveFileDialog Export2File";
sfd.Filter = "Text File (.txt) | *.txt";
if (sfd.ShowDialog() == DialogResult.OK)
{
filename = sfd.FileName.ToString();
if (filename != "")
{
using (StreamWriter sw = new StreamWriter(filename))
{
foreach (ListViewItem item in lv.Items)
{
sw.WriteLine("{0}{1}{2}", item.SubItems[0].Text, splitter, item.SubItems[1].Text);
}
}
}
}
}

Related

C#, saving from menu strip, and save as button

I am trying to save my rich text box content to a a file. However I am getting the error when I am trying to save a new file. Save as works as expected. Any suggestions. Thank you
System.ArgumentException: 'Empty path name is not legal.'
My code for the save and save as button are as follows:
OpenFileDialog file_open = new OpenFileDialog();
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveDlg = new SaveFileDialog();
string filename = "";
// To filter files from SaveFileDialog
saveDlg.Filter = "Rich Text File (*.rtf)|*.rtf|Plain Text File (*.txt)|*.txt";
saveDlg.DefaultExt = "*.rtf";
saveDlg.FilterIndex = 1;
saveDlg.Title = "Save the contents";
filename = file_open.FileName;
RichTextBoxStreamType stream_type;
// Checks the extension of the file to save
if (filename.Contains(".txt"))
stream_type = RichTextBoxStreamType.PlainText;
else
stream_type = RichTextBoxStreamType.RichText;
richTextBox1.SaveFile(filename, stream_type);
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveDlg = new SaveFileDialog();
string filename = "";
// To filter files from SaveFileDialog
saveDlg.Filter = "Rich Text File (*.rtf)|*.rtf|Plain Text File (*.txt)|*.txt";
saveDlg.DefaultExt = "*.rtf";
saveDlg.FilterIndex = 1;
saveDlg.Title = "Save the contents";
DialogResult retval = saveDlg.ShowDialog();
if (retval == DialogResult.OK)
filename = saveDlg.FileName;
else
return;
RichTextBoxStreamType stream_type;
if (saveDlg.FilterIndex == 2)
stream_type = RichTextBoxStreamType.PlainText;
else
stream_type = RichTextBoxStreamType.RichText;
richTextBox1.SaveFile(filename, stream_type);
MessageBox.Show("File Saved");
}

Save stream of savefiledialog in c#

In my wpf app I have an "Export" button that suppose to save some json file to chosen path.
I mean my question is how to write the file, let's say he has the path D:\somefile.json to the chosen location that the user chose from save dualog?
Here my code:
void Export_button_Click(object sender, RoutedEventArgs e)
{
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Json files (*.json)|*.json";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
}
}
This should be something like:
Copy(StreamOf(D:\somefile.json),ChosenPath)
SaveFileDialog sf = new SaveFileDialog();
sf.Filter = "Json files (*.json)|*.json";
sf.FilterIndex = 2;
sf.RestoreDirectory = true;
if (sf.ShowDialog() == DialogResult.OK)
{
System.IO.File.Copy(#"D:\somefile.json", sf.FileName, true);
}
you can use File.copy
public static void Copy(
string sourceFileName,
string destFileName)
for more info you can visit https://msdn.microsoft.com/en-us/library/c6cfw35a(v=vs.110).aspx

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

Overwriting a text file from RichTextBox

Now if you write the text and click on the save button, OpenFileDialog will appear. If you finish something in the same document and click on the save button again, you need to select the save location again. How to make that when saving the same file you do not need to create a new file each time, and just overwrite the current one? Sorry for my English.
private void buttonSave_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Rich Text File | *.rtf";
if (sfd.ShowDialog() == DialogResult.OK)
{
richTextBox1.SaveFile(sfd.FileName);
}
else
{
}
}
It sure is, you just need to remember the last file path you saved and not display the dialog again the next time around; something like this should help:
void Main()
{
Save();
}
private string _filePath = "";
void Save()
{
var overwrite = false;
if (!string.IsNullOrEmpty(_filePath))
{
var res =
MessageBox.Show("Would you like to overwrite your last saved file?", "Overwrite?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1,
MessageBoxOptions.DefaultDesktopOnly, false);
if (res == DialogResult.Cancel) return;
if (res == DialogResult.No) overwrite = false;
if (res == DialogResult.Yes) overwrite = true;
}
if (!overwrite)
{
var sfd = new SaveFileDialog();
sfd.Filter = "Rich Text File|*.rtf";
var res = sfd.ShowDialog();
if (res != DialogResult.OK) return;
_filePath = sfd.FileName;
}
// do the richTextBox.SaveFile(_filePath) here.
}
In this example it:
CHECK IF FILE PATH ALREADY SET
IF NOT THEN
ASK USER IF THEY WANT TO OVERWRITE THE LAST FILE
IF CANCEL THEN DON'T SAVE
IF YES THEN SET OVERWRITE TO TRUE
IF NO THEN SET OVERWRITE TO FALSE
END IF
CHECK IF OVERWRITING
IF OVERWRITING THEN
SHOW SAVE FILE DIALOG
IF USER DIDN'T CLICK OK THEN DON'T SAVE
IF USER CLICKED OK, SET THE NEW FILE PATH TO USE
END IF
SAVE THE FILE USING THE NOW-REMEMBERED FILE PATH
Perhaps:
private void SaveButton_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = #"C:\";
saveFileDialog1.Title = "Save text Files";
saveFileDialog1.CheckFileExists = true;
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.DefaultExt = "txt";
saveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = saveFileDialog1.FileName;
}
}
Example from: http://www.c-sharpcorner.com/uploadfile/mahesh/savefiledialog-in-C-Sharp/
Might help some?
private string filePath = string.Empty;
private void SaveButton_Click(object sender, EventArgs e)
{
if (File.Exists(filePath))
{
byte[] buffer = Encoding.ASCII.GetBytes(richTextBox1.Text);
MemoryStream ms = new MemoryStream(buffer);
//write to file
FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write);
ms.WriteTo(file);
file.Close();
ms.Close();
}
else
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Rich Text File | *.rtf";
sfd.OverwritePrompt = false;
if (sfd.ShowDialog() == DialogResult.OK)
{
richTextBox1.SaveFile(sfd.FileName);
filePath = sfd.FileName;
}
}
}
you can use sfd.OverwritePrompt = false; property to avoid prompt messagebox if file already exists, is this what you are looking for ?

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

Categories