Getting the path of a file from the SaveFileDialog to a string - c#

In my form I have a button that launches the SaveFileDialog module. Then when I load a file, I want to save the path as a string and put that text into a text box on the form. I'm not sure how to do this, or even where to start?

Well the problem with your question is that you say when you "load a file", but you cannot load a file from the SaveFileDialog module. However, if you are opening a file via the OpenFileDialog module, then you are able to use this solution to get the directory path of the file you just loaded:
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
var directoryPath = Path.GetDirectoryName(openFileDialog1.FileName);
if(!string.IsNullOrEmpty(directoryPath))
textBox1.Text = directoryPath;
}
Otherwise, if you are wanting to get the file path of whatever file you saved originally, you can use pretty much the same solution to get the directory path:
if (saveFileDialog1.ShowDialog(this) == DialogResult.OK)
{
var directoryPath = Path.GetDirectoryName(saveFileDialog1.FileName);
if (!string.IsNullOrEmpty(directoryPath))
textBox1.Text = directoryPath;
}

Related

How to set a Initial file name in a SaveFileDialog?

I created a script for a save-file-dialog to save a file. It has the Initial location set to the desktop. Now my question is, how do i set an initial "name" for the file in the dialog?
Here's my code:
private SaveFileDialog save = new SaveFileDialog();
private void Information(string Basic, string nameoffile, string program)
{
if (doingsomething) return;
System.Windows.Forms.MessageBox.Show($"Please select where you would like to store the file)"
save.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (save.ShowDialog() == DialogResult.OK)
If there is an answer for this, please point where I can find it. Because i don't know the exact keyword.
You can asssign default name like
save.FileName="File1";

Export Crystal Report To Excel - Specify Directory

I have crystal reports (using C#) that I pull and want to export to Excel. I manage to pull and export the report just fine. But in the code I manually specify the export directory.
Code:
myEquipCalRPT.ExportToDisk(ExportFormatType.Excel, "C:\\Temp\\ReportName.xls");
I know the path must be a string value. How can I ask the user where he/she wants to export the report to (and give it a name) instead of manually specifying the path in the code?
I tried using "SaveFileDialog" with the code below and then I get this exception: "Additional information: The given path's format is not supported.". This allows the user to specify a file name, although I noticed the file type just below the file name box is not set, and have no types to select from either.
SaveFileDialog browser = new SaveFileDialog();
string directoryPath = "";
ienter code here`f (browser.ShowDialog() == DialogResult.OK)
{
directoryPath = browser.ToString(); // prints path
}
myEquipCalRPT.ExportToDisk(ExportFormatType.Excel, directoryPath);
If I use "FolderBrowserDialog", I get the error: "Additional information: Access to the path 'C:\Directory' is denied." which I suspect is due to only giving a directory path, but no file name.
FolderBrowserDialog browser = new FolderBrowserDialog();
string directoryPath = "";
if (browser.ShowDialog() == DialogResult.OK)
{
directoryPath = browser.SelectedPath; // prints path
}
myEquipCalRPT.ExportToDisk(ExportFormatType.Excel, directoryPath);
If I try the following, I get no error, but also no file is saved:
FolderBrowserDialog browser = new FolderBrowserDialog();
string directoryPath = "";
string FileName = "ExcelExport.xls";
string Path = directoryPath + FileName;
if (browser.ShowDialog() == DialogResult.OK)
{
directoryPath = browser.SelectedPath; // prints path
}
myEquipCalRPT.ExportToDisk(ExportFormatType.Excel, Path);
Also, how can I export to .xlsx instead of .xls? I can specify the extension in the path as .xlsx, but it does not want to open. Need to remove the X at the end to make it work.
I ended up with this code to get the path correct as the path was given through as "System.Windows.Forms.SaveFileDialog: Title: , FileName: C:\Temp\test.xls" and not "C:\Temp\test.xls" with all the dialog boxes.
SaveFileDialog browser = new SaveFileDialog();
string directoryPath = "";
if (browser.ShowDialog() == DialogResult.OK)
{
directoryPath = browser.FileName.ToString();
}
And the you can use one of these lines to write the file, depending on which way you chose to use export the report:
myRPT.ExportToDisk(ExportFormatType.Excel, "C:\\Temp\\AMCMaintTempExcelReportFile.xls")
CrDiskFileDestinationOptions.DiskFileName = directoryPath;
myRPT.ExportToDisk(ExportFormatType.Excel, directoryPath);

Create a “Open” Dialog Button and get the the file name with extension .dat

I want to create a browse (OpenFile Dialog) Button to search my local drive and then write out the selected file name (not the full path ) to a TextBox. It should show Only .dat extension files.
I am using Visual Studio 2008
Any help much appreciated!
Next time you ask anything, show some examples of what you have tried please.
private string GetDatFileName()
{
// Create Open File Dialog with the correct filter
using (OpenFileDialog ofd = new OpenFileDialog()) {
ofd.Filter = "dat-file (*.dat) | *.dat";
string fileNameAndFolder = "";
string fileName = "";
// Get file plus folder.
if (ofd.ShowDialog() == DialogResult.OK)
{
fileNameAndFolder = ofd.FileName;
// Split folder and filename
fileName = Path.GetFileName(fileNameAndFolder);
}
// Return the fileName;
return fileName;
}
}
What I have done here is create an OpenFileDialog and set its filter to the required "dat"-format. Only .dat-files will show up in the browserdialog.
Next, you show the dialog and check if the result is OK. If the result is, you will get the full filename (with folder) into a variable. All thats left then, is to get the filename from fileNameAndFolder.

Creating and saving files in C#

I need to create and write to a .dat file. I'm guessing that this is pretty much the same process as writing to a .txt file, but just using a different extension.
In plain english I would like to know how to:
-Create a .dat file
-Write to it
-And save the file using SaveFileDialog
There are a few pages that I've been looking at, but I think that my best explanation will come from this site because it allows me to state exactly what I need to learn.
The following code is what I have at the moment. Basically it opens a SaveFileDialog window with a blank File: section. Mapping to a folder and pressing save does not save anything because there is no file being used. Please help me use this to save files to different locations.
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "";
dlg.DefaultExt = "";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string filename = dlg.FileName;
}
Pages that I've been looking at:
-http://msdn.microsoft.com/en-us/library/8bh11f1k.aspx
-http://social.msdn.microsoft.com/Forums/en-US/cd0b129f-adf1-4c4f-9096-f0662772c821/how-to-use-savefiledialog-for-save-text-file
-http://msdn.microsoft.com/en-us/library/system.io.file.createtext(v=vs.110).aspx
Note that the SaveFileDialog only yields a filename but does not actually save anything.
var sfd = new SaveFileDialog {
Filter = "Text Files (*.txt)|*.txt|All files (*.*)|*.*",
// Set other options depending on your needs ...
};
if (sfd.ShowDialog() == true) { // Returns a bool?, therefore the == to convert it into bool.
string filename = sfd.FileName;
// Save the file ...
}
Use the filename you are getting from the SaveFileDialog and do the following:
File.WriteAllText(filename, contents);
That's all if you intend to write text to the file.
You can also use:
File.WriteAllLines(filename, contentsAsStringArray);
using(StreamWriter writer = new StreamWriter(filename , true))
{
writer.WriteLine("whatever your text is");
}

Save a browsed file to a pre-defined folder using c#

I am working on a WinForm Application using c#. I am using a button to browse for an image file (.jpeg or .bmp). When the user browses the file and clicks ok, on the click of another "Proceed or Update" button, I want that the browsed file should be renamed and saved to a predefined directory where all image files will be saved by default, without much user interaction!
How can I achieve this? I have used openFileDialog for browsing the file, but dont know what else to do.
//detination filename
string newFileName = #"C:\NewImages\NewFileName.jpg";
// if the user presses OK instead of Cancel
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
//get the selected filename
string filename = openFileDialog1.FileName;
//copy the file to the new filename location and overwrite if it already exists
//(set last parameter to false if you don't want to overwrite)
System.IO.File.Copy(filename, newFileName, true);
}
More information on the Copy method.
First you have to implement a copy function that can make unique file names:
private void CopyWithUniqueName(string source,
string targetPath,
string targetFileName)
{
string fileName = Path.GetFileNameWithoutExtension(targetFileName);
string extension = Path.GetExtension(targetFileName);
string target = File.Exists(Path.Combine(targetPath, targetFileName);
for (int i=1; File.Exists(target); ++i)
{
target = Path.Combine(targetPath, String.Format("{0} ({1}){2}",
targetFileName, i, extension));
}
File.Copy(source, target);
}
Then you can use it, suppose defaultTargetPath is the default target file where to copy images and defaultFileName is the default file name for images:
void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() != DialogResult.OK)
return;
CopyWithUniqueName(openFileDialog1.FileName,
defaultTargetPath, defaultFileName);
}
In case of multiple selection:
foreach (string fileName in openFileDialog1.FileNames)
{
CopyWithUniqueName(fileName,
defaultTargetPath, defaultFileName);
}
You'll get this (suppose defaultFileName is "Image.png"):
Source Target
A.png Image.png
B.png Image (1).png
C.png Image (2).png
You can do that with the File.Copy()-method. Just put the predefined directory and the new filename as the destination parameter.
For more info see here

Categories

Resources