in my code i am writing text boxes data to a text file using save file dialog, which will save my text box data to a specified text file.and my problem is i need to retrieve back file data to respective text boxes when ever user required ...how can i do it?
private void SaveData_Click(object sender, EventArgs e)
{
// Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = "c:\\";
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
using (StreamWriter objWriter = new StreamWriter(myStream))
{
objWriter.Write(textBox1.Text);
objWriter.Write(",");
objWriter.Write(textBox2.Text);
objWriter.Write(",");
objWriter.Write(textBox3.Text);
objWriter.Write(",");
objWriter.Write(textBox4.Text);
MessageBox.Show("Details have been saved");
}
myStream.Close();
}
}
}
private void Retrieve_Click(object sender, EventArgs e)
{
//Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
textBox1.Text = (myStream).ToString();
textBox2.Text = ().ToString();
textBox3.Text = ().Tostring();
textBox4.text = ().Tostring();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
You need to use an OpenFileDialog Control and pass it to the ReadAllText Method ..
Here is an Example :
myAmazingTextBox.Text = File.ReadAllText(openFileDialog1.FileName);
Save the location where user saves data.\
Next time you should read the path first.
You can save the saveFileDialog1.FileName.
Use the code below to retrieve the text saved in the file (code changed within try block)
private void Retrieve_Click(object sender, EventArgs e)
{
//Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
// Read all text stored in the file
string fileData = File.ReadAllText(openFileDialog1.FileName);
// As you are appending textbox data using comma as separator,
// so split the text read from file on comma separator
string[] parts = fileData.Split(',');
// as there were 4 textboxes, so after split, the 'parts' array should contain 4 elements, otherwise, the file/data is invalid
if(parts.Length != 4)
{
MessageBox.Show("Invalid source file.");
return;
}
// set the respective values into the textboxes
textBox1.Text = parts[0];
textBox2.Text = parts[1];
textBox3.Text = parts[2];
textBox4.text = parts[3];
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
I would like to suggest that you don't use comma as a separator as the user may enter text which contains comma in the content. I would suggest that you encode the text into Base64 string (which contains only A-Za-z0-9 with additional two characters which does not contain comma. So, you can separate the base64 encoded string with comma separator as then you will be 100% sure that comma is only the separator and not the part of content.
While reading, decode the base64 string and show into textboxes.
Related
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");
}
I am trying to make a try catch that will check if the file in filelocation exists or not.
If it doesnt i want the open file dialog to open and allow user to be able choose the text file (and only a text file) and read the file location of the selected file and use that as the file location sting for the sream reader
any time i use this the file location will be right until the end. instead of the file name it will have bin/debug/ok
try
{
if (!File.Exists(filelocation))
{
throw new FileNotFoundException();
}
else
{
StreamReader question = new StreamReader(filelocation);
}
}
catch (System.IO.FileNotFoundException)
{
MessageBox.Show("File containing the questions not found");
OpenFileDialog OFD = new OpenFileDialog();
DialogResult result = OFD.ShowDialog();
string filelocation = result.ToString();
StreamReader question = new StreamReader(filelocation);
}
add this
OFD .Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
the result will be:
try
{
if (!File.Exists(filelocation))
{
throw new FileNotFoundException();
}
else
{
StreamReader question = new StreamReader(filelocation);
}
}
catch (System.IO.FileNotFoundException)
{
MessageBox.Show("File containing the questions not found");
OpenFileDialog OFD = new OpenFileDialog();
OFD .Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
DialogResult result = OFD.ShowDialog();
string filelocation = result.ToString();
StreamReader question = new StreamReader(filelocation);
}
This takes into account whether User did not select a File from the File Dialog or whether invalid file is selected...
StreamReader ReadME;
if (!File.Exists(termfilelocation))
{
MessageBox.Show("File containing the questions not found");
OpenFileDialog OFD = new OpenFileDialog();
OFD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
// this will filter out any file that isnt a text file
ofd.CheckFileExists = true;//this will not allow invalid files.
DialogResult dr = OFD.ShowDialog();
if (dr == DialogResult.Cancel)
{
//User did not select a file.
return;
}
String result = OFD.FileName;
ReadME = new StreamReader(result);
termfilelocation = result;
}
else
{
ReadME = new StreamReader(termfilelocation);
}
I fixed it myslef so anybody having similar problems heres how to fix it
try
{
if (!File.Exists(termfilelocation))
{
throw new FileNotFoundException();
}
else
{
StreamReader reader = new StreamReader(termfilelocation);
}
}
catch (System.IO.FileNotFoundException)
{
MessageBox.Show("File containing the questions not found");
// this will display a message box sying whats in ("")
OpenFileDialog OFD = new OpenFileDialog();
// this will create a new open file dialog box
OFD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
// this will filter out any file that isnt a text file
DialogResult = OFD.ShowDialog();
String result = OFD.FileName;
// this will give the result to be the file name
// that was choosen in the open file dialog box
StreamReader reader = new StreamReader(result);
termfilelocation = result;
}
I am trying to use a OpenFileDialog to let the user select a local file that can interact with my app. The file can be in use when the user selects it as I really only want to get the file's path. My issue is that if I try doing this with a OpenFileDialog, when the user presses "open", it actually tries to open the file even though I don't call for opening anywhere. Since the file is in use, it throws an error.
Is there any way for me to present a dialog for a user to just select a file an do nothing else?
Heres my current code:
DialogResult result = this.qbFilePicker.ShowDialog();
if (result == DialogResult.OK)
{
string fileName = this.qbFilePicker.FileName;
Console.WriteLine(fileName);
}
Make sure you are using
using System.Windows.Forms;
Then the following code from MSDN will not open your file unless you explicitly uncomment the bit that opens the file :)
(Take out the bits that don't pertain to you such as the .txt filter etc)
private void Button_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string fileName = openFileDialog1.FileName;
Console.WriteLine(fileName);
//to open the file
/*
try
{
Stream myStream = null;
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
* */
}
}
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);
}
}
}
I am trying to read a .txt file into a multi-line text box with the following code. I have gotten the file dialog button to work perfectly, but I am not sure how to get the actual text from the fiile into the textbox. Here is my code. Can you help?
private void button_LoadSource_Click(object sender, EventArgs e)
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
if you just need the complete text, you should use the function File.ReadAllText - pass it the FileName/Path selected in the dialoge (openFileDialog1.FileName).
to load for example the content into a textbox, you can write:
textbox1.Text = File.ReadAllText(openFileDialog1.FileName);
opening and using streams is a little bit more complicated, for that you should look up the using - statement