File Open/Save Dialog - c#

I am using my own Custom View to show the files and folders and also using a search box to jump to a specific folder. In that case How to send a message to File Open/Save dialog to enforce it to change the current displayed folder.
e.g. If the dialog shows files and folders of current displaying folder "C:\", I want an API (or any piece of code) to enforce to change the current folder to "D:\"

You can have the dialog open at a specific directory using InitialDirectory.
If you want to control what the dialog does at runtime, that's a bit more complex.

Set SaveFileDialog.InitialDirectory after you create it, but before you open it.
For example:
Stream myStream = null;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1 .InitialDirectory = "d:\\" ;
saveFileDialog1 .Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
saveFileDialog1 .FilterIndex = 2 ;
saveFileDialog1 .RestoreDirectory = true ;
if(saveFileDialog1 .ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = saveFileDialog1 .OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not save file to disk. Original error: " + ex.Message);
}
}

set InitialDirectory property to any path

Related

C# winform File.Copy from a SaveDialog

I am attempting to copy a .txt from my application directory or some kind an export feature to users desire path and filename using savedialog on C# my code is below.
private void button2_Click(object sender, EventArgs e)
{
string directory = AppDomain.CurrentDomain.BaseDirectory + "output.txt";
using (SaveFileDialog dialog = new SaveFileDialog())
{
dialog.Filter = "txt files (*.txt);
dialog.FilterIndex = 2;
dialog.RestoreDirectory = true;
if (dialog.ShowDialog() == DialogResult.OK)
{
File.Copy(directory, Path.GetDirectoryName(dialog.FileName) + dialog.FileName);
}
}
}
But I am getting an error
The given path's format is not supported.
I am new with C# and want to understand this error and in addition, I want to set the file name extention default as .txt also, any suggestion would be great.
There are a couple of things you need to change.
First, of course, is your copy call. This line makes no sense
File.Copy(directory, Path.GetDirectoryName(dialog.FileName) + dialog.FileName);
dialog.FileName contains already the full file name of your destination file. So there is no need to extract the directory and then add all the path again. Write just
File.Copy(directory, dialog.FileName);
But this creates a possible error. What if your user doesn't change the destination folder to another directory? You end up writing on the same file you want to read.
So I would add a sanity check like this
if(directory == dialog.FileName)
MessageBox.Show("Copy","Choose a different output folder");
else
File.Copy(directory, dialog.FileName);
Finally, if you want to force the output file to have always the .TXT extension you could add this line to the SaveDialog configuration
// Fix also your filter property. The one you have is invalid
dialog.Filter = "txt files (*.txt)|*.txt";
dialog.FilterIndex = 0; // 2 ?? There is no index 2 in your filter string
dialog.RestoreDirectory = true;
// Force the .TXT extension
dialog.AddExtension = true;

Save DIalogue that copies/loads another file

I am trying to save a file, but the actual file is already built and saved in a temp location, and I just want to move/copy that pre-built file to wherever the user chooses with the save dialogue.
What I have right now is this
fileName = the pathway of the file that is already built.
private void SaveFile()
{
SaveFileDialog savefile = new SaveFileDialog();
savefile.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
if (savefile.ShowDialog() == DialogResult.OK)
{
using (StreamWriter sw = new StreamWriter(savefile.FileName))
sw.WriteLine(fileName);
}
}
Obviously right now this just writes the pathway to a text file, but I am trying to find a way to basically copy that file to wherever this user specifies.
you can do like
if (savefile.ShowDialog() == DialogResult.OK)
{
// you can use File.Copy
System.IO.File.Copy(fileName, saveFile.Filename);
}

Win Form: SaveFileDialog

I added the following piece of code to a save button:
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.Create);
StreamWriter writer = new StreamWriter(fs);
writer.Write(twexit.Text); // twexit is previously created
writer.Close();
fs.Close();
}
When I type the name of the file and click save, it says that file does not exist. I know it does not exist but I set FileMode.Create. So, shouldnt it create file if it does not exist?
There is an option CheckFileExists in SaveFileDialog which will cause the dialog to show that message if the selected file doesn't exist. You should leave this set to false (this is the default value).
You can simply use this:
File.WriteAllText(saveFileDialog1.FileName, twexit.Text);
instead of lot of code with stream. It create new file or overwrite it.
File is class of System.Io . If you want to say if file exist, use
File.Exist(filePath)
Bye
Use like this:
SaveFileDialog dlg = new SaveFileDialog();
dlg.Filter = "csv files (*.csv)|*.csv";
dlg.Title = "Export in CSV format";
//decide whether we need to check file exists
//dlg.CheckFileExists = true;
//this is the default behaviour
dlg.CheckPathExists = true;
//If InitialDirectory is not specified, the default path is My Documents
//dlg.InitialDirectory = Application.StartupPath;
dlg.ShowDialog();
// If the file name is not an empty string open it for saving.
if (dlg.FileName != "")
//alternative if you prefer this
//if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK
//&& dlg.FileName.Length > 0)
{
StreamWriter streamWriter = new StreamWriter(dlg.FileName);
streamWriter.Write("My CSV file\r\n");
streamWriter.Write(DateTime.Now.ToString());
//Note streamWriter.NewLine is same as "\r\n"
streamWriter.Write(streamWriter.NewLine);
streamWriter.Write("\r\n");
streamWriter.Write("Column1, Column2\r\n");
//…
streamWriter.Close();
}
//if no longer needed
//dlg.Dispose();

How to disable OpenFileDialog opening files automatically?

I am using following code to select a file to import in a Windows Forms project.
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "C# Corner Open File Dialog";
fdlg.InitialDirectory = #"c:\";
fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
fdlg.FilterIndex = 2;
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
txtpath.Text = fdlg.FileName;
}
The problem is that the selected file is opened in the background which I don't want. What can I do to just get the path of selected file without opening it?
Showing an OpenFileDialog and the user selecting a file does not open the file. The file can be opened by calling OpenFile. In the code you posted the file is not opened. That code appears to be copied from an example on MSDN. The rest of the code from that example is here:
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null) // File is opened here.
{
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 the file is being opened when you don't want it opened then the problem must be somewhere else and not in the code you posted. It is possible for example that you have not closed the file (for example by using Dispose) after you finished using it last time.

uploading picture

Good day
Creating an Inventory system
created a db in sql, In visual c#, I created a form where products will be entered and allowing the user to upload an image of the item, How do I go about doing it?
I'm a c++ programmer, newly into visual c#
Thanks
Here is an older post on uploading on uploading a file.
Assuming you'd want to save the images in the database as well... You need to allow the user to select an image from his/her own harddisk (Open File Dialog), and then read the bytes and send them to the database (ADO.NET's DbCommand). ADO.NET supports streams for BLOBS.
Here is a example of the Open File Dialog:
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "images (*.png)|*.png|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
using (Stream myStream = openFileDialog1.OpenFile())
{
if (myStream != null)
{
// do something with the stream bytes here....
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}

Categories