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 have been just hard coding a save name/location, but now I need to ask the user for the save location and file name. I have this syntax, but how do I actually pass the selected location & input file name to my ToExcel() method to know the file name and save locaiton?
private void btnSave_Click(object sender, EventArgs e)
{
//Creating Save File Dialog
SaveFileDialog save = new SaveFileDialog();
//Showing the dialog
save.ShowDialog();
//Setting default directory
save.InitialDirectory = #"C:\";
save.RestoreDirectory = true;
//Setting title
save.Title = "Select save location and input file name";
//filtering to only show .xml files in the directory
save.DefaultExt = "xml";
//Write Data To Excel
ToExcel();
}
private void ToExcel()
{
var file = new FileInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "Test_" + DateTime.Now.ToString("M-dd-yyyy-HH.mm.ss") + ".xlsx"));
using (var package = new ExcelPackage(file))
{
ExcelWorksheet ws = package.Workbook.Worksheets.Add("Test");
ws.Cells[1, 1].Value = "One";
ws.Cells["A1:C1"].Style.Font.Bold = true;
package.Save();
MessageBox.Show("Saved!");
}
}
Firstly ShowDialog should be the last line of your call, after you have configured it
then use the FileName Property to access the selected Filename
finally pass that to whatever you need to pass it to ie
private void btnSave_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.InitialDirectory = #"C:\";
save.RestoreDirectory = true;
save.Title = "Select save location file name";
save.DefaultExt = "xml"; // surely should be xlsx??
//Showing the dialog
if(save.ShowDialog() == DialogResult.OK)
{
ToExcel(save.FileName);
}
}
private void ToExcel(string saveFile){...}
also if you want to get the Directorty of a FileInfo check the FileInfo.Directory property
Hey there i started learning C# a few days ago and I'm trying to make a program that copies and pastes files (and replaces if needed) to a selected directory but I don't know how to get the directory and file paths from the openfiledialog and folderbrowserdialog
what am I doing wrong?
Here's the code:
namespace filereplacer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void direc_Click(object sender, EventArgs e)
{
string folderPath = "";
FolderBrowserDialog directchoosedlg = new FolderBrowserDialog();
if (directchoosedlg.ShowDialog() == DialogResult.OK)
{
folderPath = directchoosedlg.SelectedPath;
}
}
private void choof_Click(object sender, EventArgs e)
{
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;
choofdlog.ShowDialog();
}
private void replacebtn_Click(object sender, EventArgs e)
{
// This is where i'm having trouble
}
public static void ReplaceFile(string FileToMoveAndDelete, string FileToReplace, string BackupOfFileToReplace)
{
File.Replace(FileToMoveAndDelete, FileToReplace, BackupOfFileToReplace, false);
}
}
For OpenFileDialog:
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;
if (choofdlog.ShowDialog() == DialogResult.OK)
{
string sFileName = choofdlog.FileName;
string[] arrAllFiles = choofdlog.FileNames; //used when Multiselect = true
}
For FolderBrowserDialog:
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.Description = "Custom Description";
if (fbd.ShowDialog() == DialogResult.OK)
{
string sSelectedPath = fbd.SelectedPath;
}
To access selected folder and selected file name you can declare both string at class level.
namespace filereplacer
{
public partial class Form1 : Form
{
string sSelectedFile;
string sSelectedFolder;
public Form1()
{
InitializeComponent();
}
private void direc_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
//fbd.Description = "Custom Description"; //not mandatory
if (fbd.ShowDialog() == DialogResult.OK)
sSelectedFolder = fbd.SelectedPath;
else
sSelectedFolder = string.Empty;
}
private void choof_Click(object sender, EventArgs e)
{
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;
if (choofdlog.ShowDialog() == DialogResult.OK)
sSelectedFile = choofdlog.FileName;
else
sSelectedFile = string.Empty;
}
private void replacebtn_Click(object sender, EventArgs e)
{
if(sSelectedFolder != string.Empty && sSelectedFile != string.Empty)
{
//use selected folder path and file path
}
}
....
}
NOTE:
As you have kept choofdlog.Multiselect=true;, that means in the OpenFileDialog() you are able to select multiple files (by pressing ctrl key and left mouse click for selection).
In that case you could get all selected files in string[]:
At Class Level:
string[] arrAllFiles;
Locate this line (when Multiselect=true this line gives first file only):
sSelectedFile = choofdlog.FileName;
To get all files use this:
arrAllFiles = choofdlog.FileNames; //this line gives array of all selected files
Use the Path class from System.IO. It contains useful calls for manipulating file paths, including GetDirectoryName which does what you want, returning the directory portion of the file path.
Usage is simple.
string directoryPath = System.IO.Path.GetDirectoryName(choofdlog.FileName);
you can store the Path into string variable like
string s = choofdlog.FileName;
To get the full file path of a selected file or files, then you need to use FileName property for one file or FileNames property for multiple files.
var file = choofdlog.FileName; // for one file
or for multiple files
var files = choofdlog.FileNames; // for multiple files.
To get the directory of the file, you can use Path.GetDirectoryName
Here is Jon Keet's answer to a similar question about getting directories from path
Create this class as Extension:
public static class Extensiones
{
public static string FolderName(this OpenFileDialog ofd)
{
string resp = "";
resp = ofd.FileName.Substring(0, 3);
var final = ofd.FileName.Substring(3);
var info = final.Split('\\');
for (int i = 0; i < info.Length - 1; i++)
{
resp += info[i] + "\\";
}
return resp;
}
}
Then, you could use in this way:
//ofdSource is an OpenFileDialog
if (ofdSource.ShowDialog(this) == DialogResult.OK)
{
MessageBox.Show(ofdSource.FolderName());
}
Your choofdlog holds a FileName and FileNames (for multi-selection) containing the file paths, after the ShowDialog() returns.
A primitive quick fix that works.
If you only use OpenFileDialog, you can capture the FileName, SafeFileName, then subtract to get folder path:
exampleFileName = ofd.SafeFileName;
exampleFileNameFull = ofd.FileName;
exampleFileNameFolder = ofd.FileNameFull.Replace(ofd.FileName, "");
I am sorry if i am late to reply here but i just thought i should throw in a much simpler solution for the OpenDialog.
OpenDialog ofd = new OpenDialog();
var fullPathIncludingFileName = ofd.Filename; //returns the full path including the filename
var fullPathExcludingFileName = ofd.Filename.Replace(ofd.SafeFileName, "");//will remove the filename from the full path
I have not yet used a FolderBrowserDialog before so i will trust my fellow coders's take on this. I hope this helps.
String fn = openFileDialog1.SafeFileName;
String path = openFileDialog1.FileName.ToString().Replace(fn, "");
I am getting a error when i decrypt my file.
"The path is not of a legal form"
if i direct the privateKeyLocation manually e.g. string privateKeyLocation = #"c:\privatekey.txt", its okay and runs fine.
But i want to find the key file myself using open file dialog.
Anybody know what went wrong?
Thanks in advance!
private void decryptFileButton_Click(object sender, EventArgs e)
{
string inputFileLocation = attachmentTextBox.Text;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.RestoreDirectory = true;
string privateKeyLocation = new FileInfo(openFileDialog1.FileName).ToString();
string privateKeyPassword = passphrase2TextBox.Text;
string outputFile = #"c:\Original.txt";
// decrypt and obtain the original file name
// of the decrypted file
string originalFileName =
pgp.DecryptFile(inputFileLocation,
privateKeyLocation,
privateKeyPassword,
outputFile);
}
Just a simple matter of showdialog() and its result:
private void decryptFileButton_Click(object sender, EventArgs e)
{
string inputFileLocation = attachmentTextBox.Text;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string privateKeyLocation = new FileInfo(openFileDialog1.FileName).ToString();
string privateKeyPassword = passphrase2TextBox.Text;
string outputFile = #"c:\Original.txt";
decrypt and obtain the original file name
of the decrypted file
string originalFileName =
pgp.DecryptFile(inputFileLocation,
privateKeyLocation,
privateKeyPassword,
outputFile);
}
}
I want to read a text file which contains more than one paragraph separated by new lines. How to read every paragraph alone in RichTextBox and how to transfer to the next paragraph by button next and back to the first paragraph by button previous designed in the form. My code
private void LoadFile_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
dialog.Title = "Select a text file";
dialog.ShowDialog();
if (dialog.FileName != "")
{
System.IO.StreamReader reader = new System.IO.StreamReader(dialog.FileName);
string Text = reader.ReadToEnd();
reader.Close();
this.Input.TextChanged -= new System.EventHandler(this.Input_TextChanged);
Input.Clear();
Input.Text = Text;
}
}
Use this code.
var text = File.ReadAllText(inputFilePath);
var paragraphs = text .Split('\n');
paragraphs will be an array of strings containing all the paragraphs.
Use String.split() to split it at '\n'.
Afterwards iterate through the array on the Button next.
private string[] paragraphs;
private int index = 0;
private void LoadFile_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter =
"txt files (*.txt)|*.txt|All files (*.*)|*.*";
dialog.Title = "Select a text file";
dialog.ShowDialog();
if (dialog.FileName != "")
{
System.IO.StreamReader reader = new System.IO.StreamReader(dialog.FileName);
string Text = reader.ReadToEnd();
reader.Close();
this.Input.TextChanged -= new System.EventHandler(this.Input_TextChanged);
Input.Clear();
paragraphs = Text.Split('\n');
index = 0;
Input.Text = paragraphs[index];
}
}
private void Next_Click(object sender, EventArgs e)
{
index++;
Input.Text = paragraphs[index];
}
(I know this might not be the most elegant solution but it should give an idea on what to do.)