How to copy a file to pre-destinated folder using File.OpenDialog? - c#

Using File.OpenDialog how can i make a copy of selected files to a certain (predeclared or even better from a string variable taken from textbox) location?
I assume i can firstly simply use the ofd method, but where to determine the location to copy?
InitializeComponent();
PopulateTreeView();
this.treeView1.NodeMouseClick +=
new TreeNodeMouseClickEventHandler(this.treeView1_NodeMouseClick);
OpenFileDialog ofd1 = new OpenFileDialog();
and for the button:
private void button3_Click(object sender, EventArgs e)
{
if (ofd1.ShowDialog() == DialogResult.OK)
{ }
}

If I understood correctly, then once you select the file from open file dialog, you want to copy it to a certain location. Then you can use something like this code -
if (this.openFileDialog1.ShowDialog()== System.Windows.Forms.DialogResult.OK)
{
var fileName = this.openFileDialog1.FileName;
File.Copy(fileName, "DestinationFilePath");
}
Or in case of multiple selected file, something like this -
if (this.openFileDialog1.ShowDialog()== System.Windows.Forms.DialogResult.OK)
{
var fileNames = this.openFileDialog1.FileNames;
foreach (var fileName in fileNames)
{
File.Copy(fileName, "DestinationFilePath/" + fileName);
}
}

Check out the foreach loop in this for iterating through all of the files you selected using the OpenDialog.
I think this is what you're looking for in regards to actually copying the files. It takes a source directory and copies to the destination you provide.

Related

Doubleclick on saved file open my windows form but don't pick up any saved data

I created simple program for save/open practice. Made a setup and associated my program with my own datatype, called it .xxx (for practice).
I managed to Save and Open code and data from textbox but only from my program. Double click (or enter from windows-desktop) open up my WindowsForm as it is but there is an empty textbox. I want my saved file to be opened on double click in the same condition as when I open it from my program. How to set that up??
Here is the code of simple app (cant post images but it simple - got 1 label and 1 textbox with open and save buttons):
private void ButOpen_Click(object sender, EventArgs e)
{
textBox1.Text = "";
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string data = Read(openFileDialog1.FileName);
textBox1.Text = data;
}
else
{//do nothing }
}
private string Read(string file)
{
StreamReader reader = new StreamReader(file);
string data = reader.ReadToEnd();
reader.Close();
return data;
}
private void ButSave_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Something|*.xxx";
DialogResult result = saveFileDialog1.ShowDialog();
string file = saveFileDialog1.FileName.ToString();
string data = textBox1.Text;
Save(file, data);
}
private void Save(string file, string data)
{
StreamWriter writer = new StreamWriter(file);
writer.Write(data);
writer.Close();
}
NOTE:
My similar question was marked as duplicate but it is not, and this question which was referenced as duplicate Opening a text file is passed as a command line parameter does not help me.It's not the same thing...
Just wanted to find out how to configure registry so windows understand and load data inside the file, or to file save data somehow so i can open it with double click.
So someone please help. If something is not clear I will give detailed information just ask on what point.
Thanks
MSDN has some information about this:
https://msdn.microsoft.com/en-us/library/bb166549.aspx
Basically you need to create an entry in the registry so that explorer.exe knows to launch your program when that file is activated (e.g. double-clicked).
Explorer will then pass the path to the file as an argument to your program.

How do I keep track of the last folder selected by a user?

I thought using application settings would do the trick but I'm not getting it to work. This is what I have:
private void btnBrowse_Click(object sender, EventArgs e)
{
if (fbFolderBrowser.ShowDialog() == DialogResult.OK)
{
// I want to open the last folder selected by the user here.
}
When the user clicks on this button, I want to open the browse window to the last folder he accessed and save it. Next time he clicks on the button, it'll automatically select that folder.
I was thinking maybe I could use user variables where I can change at run-time but I'm not getting it to work. Can anyone give me a hand?
Go to Settings Page, Project Designer of the project which you have created and add folder path variable inside the application. Now add below code to restore the last selected folder path.
FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
folderBrowser.Description = "Select a folder to extract to:";
folderBrowser.ShowNewFolderButton = true;
folderBrowser.SelectedPath = Properties.Settings.Default.Folder_Path;
//folderBrowser.SelectedPath = project_name.Properties.Settings.Default.Folder_Path;
if (folderBrowser.ShowDialog() == DialogResult.OK)
{
if (!String.IsNullOrEmpty(Properties.Settings.Default.Folder_Path))
Properties.Settings.Default.Folder_Path = folderBrowser.SelectedPath;
Properties.Settings.Default.Folder_Path = folderBrowser.SelectedPath;
Properties.Settings.Default.Save();
}
There are two places where you can find the last folder accessed by a user:
Recent Files and Folders: It can be found here: C:\Documents and Settings\USER\Recent
Registry: In the registry to look here: HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32\OpenSaveMRU
You can use this snippet to find it:
public static string GetLastOpenSaveFile(string extention)
{
RegistryKey regKey = Registry.CurrentUser;
string lastUsedFolder = string.Empty;
regKey = regKey.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\OpenSaveMRU");
if (string.IsNullOrEmpty(extention))
extention = "html";
RegistryKey myKey = regKey.OpenSubKey(extention);
if (myKey == null && regKey.GetSubKeyNames().Length > 0)
myKey = regKey.OpenSubKey(regKey.GetSubKeyNames()[regKey.GetSubKeyNames().Length - 2]);
if (myKey != null)
{
string[] names = myKey.GetValueNames();
if (names != null && names.Length > 0)
{
lastUsedFolder = (string)myKey.GetValue(names[names.Length - 2]);
}
}
return lastUsedFolder;
}
OR
In windows XP when you press Save on a SaveFileDialog the directory where the file is saved, is set as the new current working directory (the one in Environment.CurrentDirectory).
In this way, when you reopen the FileDialog, it is opened on the same directory as before.
By setting FileDialog.RestoreDirectory = true, when you close the FileDialog the original working directory is restored.
In Windows Vista/Seven the behavior is always as FileDialog.RestoreDirectory = true.
Application settings can do the trick. A more elaborated version is here
use a Setting of type string
create a setting for each button and store the Path there. Then use
the setting as the ofd.InitialPath
using the above code example, try this:
right click your app name in Solution Explorer, click on the Settings
tab Name = Button1Path Type = String Scope = User
then use this:
private void btnBrowse_Click(object sender, EventArgs e)
{
fbFolderBrowser.InitialDirectory=this.Settings.Button1Path;
if (fbFolderBrowser.ShowDialog() == DialogResult.OK)
{
// I want to open the last folder selected by the user here.
this.Settings.Button1Path=fbFolderBrowser.SelectedPath
}
}
You can easily keep track of your last-selected folder, like this:
public String LastSelectedFolder;
private void btnBrowse_Click(object sender, EventArgs e)
{
fbFolderBrowser.InitialDirectory=this.Settings.Button1Path;
if (fbFolderBrowser.ShowDialog() == DialogResult.OK)
{
// Save Last selected folder.
LastSelectedFolder = fbFolderBrowser.SelectedPath;
}
}
I know this is a very old thread, but none of the answers point to the simplest way to re-open the file browser on user's last location.
simply define RestoreDirectory = true.
Check the example
var fd = new OpenFileDialog
{
Filter = #"All Files|*.*",
RestoreDirectory = true,
CheckFileExists = true
};
Class OpenFileDialog api reference
https://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.restoredirectory(v=vs.110).aspx
Unless I misunderstood the intention of the post, this is by far the simplest way to achieve it. However, if you do need to print this last location, then check the other

how to burn the files selected from listview in a dvd using c#.net code?

can any expert help me out to solve a problem of burning a dvd using c#.net as a front end??
i need to select files from the listview in winform and then on button click i need to burn those multiple files in the dvd..
the concept is to select the multiple files from listview then on button click it should make a folder in some desired drive.. and then it should burn that complete folder in the dvd..this whole process should be performed during a single button click....
is there any way out??
the code should be compatible to use in .net2008 and windowsXP are the given codes compatible??
im using the componenet to get the dll/class lib. from (msdn.microsoft.com/en-au/vcsharp/aa336741.aspx) but its giving me error message "there are no components in d:\filepath\burncomponent.dll to be placed on the toolbox
private void button1_Click(object sender, EventArgs e)
{
XPBurnCD cd = new XPBurnCD();
cd.BurnComplete += new NotifyCompletionStatus(BurnComplete);
MessageBox.Show(cd.BurnerDrive);
DirectoryInfo dir = new DirectoryInfo(_burnFolder);
foreach (FileInfo file in dir.GetFiles())
{
cd.AddFile(file.FullName, file.Name);
}
cd.RecordDisc(false, false);
}
private void BurnComplete(uint status)
{
MessageBox.Show("Finished writing files to disc");
}
private void button2_Click_1(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.ShowNewFolderButton = false;
fbd.Description = "Please select a folder";
fbd.RootFolder = System.Environment.SpecialFolder.DesktopDirectory;
if (fbd.ShowDialog() == DialogResult.OK)
{
_burnFolder = fbd.SelectedPath;
}
else
{
_burnFolder = string.Empty;
}
}
Check out http://msdn.microsoft.com/en-au/vcsharp/aa336741.aspx
One simple approach could be to use the command line tools dvdburn and cdburn, which are belonging to XP. For example take a look at this site.
Update
Yes, it is a console application, but you can start it within a .Net Application by using the Process class. And here you should especially take a deeper look into the StartInfo property and its members, cause here you can set the parameters or redirect the output into your program to get informations about what the program is doing.

System.Windows.Forms.SaveFileDialog does not enforce default extension

I am trying to make SaveFileDialog and FileOpenDialog enforce an extension to the file name entered by the user. I've tried using the sample proposed in question 389070 but it does not work as intended:
var dialog = new SaveFileDialog())
dialog.AddExtension = true;
dialog.DefaultExt = "foo";
dialog.Filter = "Foo Document (*.foo)|*.foo";
if (dialog.ShowDialog() == DialogResult.OK)
{
...
}
If the user types the text test in a folder where a file test.xml happens to exist, the dialog will suggest the name test.xml (whereas I really only want to see *.foo in the list). Worse: if the user selects test.xml, then I will indeed get test.xml as the output file name.
How can I make sure that SaveFileDialog really only allows the user to select a *.foo file? Or at least, that it replaces/adds the extension when the user clicks Save?
The suggested solutions (implement the FileOk event handler) only do part of the job, as I really would like to disable the Save button if the file name has the wrong extension.
In order to stay in the dialog and update the file name displayed in the text box in the FileOk handler, to reflect the new file name with the right extension, see the following related question.
You can handle the FileOk event, and cancel it if it's not the correct extension
private saveFileDialog_FileOk(object sender, CancelEventArgs e)
{
if (!saveFileDialog.FileName.EndsWith(".foo"))
{
MessageBox.Show("Please select a filename with the '.foo' extension");
e.Cancel = true;
}
}
AFAIK there's no reliable way to enforce a given file extension. It is a good practice anyway to verify the correct extension, once the dialog is closed and inform the user that he selected an invalid file if the extension doesn't match.
The nearest I've got to this is by using the FileOk event. For example:
dialog.FileOk += openFileDialog1_FileOk;
private void openFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
if(!dialog.FileName.EndsWith(".foo"))
{
e.Cancel = true;
}
}
Checkout FileOK Event on MSDN.
I ran into this same issue, and I was able to control what was shown by doing the following:
with the OpenFileDialog, the first item in the filter string was the default
openFileDialog1.Filter = "Program x Files (*.pxf)|*.pxf|txt files (*.txt)|*.txt";
openFileDialog1.ShowDialog();
with the SaveFileDialog, the second item in the filter was used as the default:
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|Program x Files (*.pxf)|*.pxf";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if (saveFileDialog1.FileName != null)
{
// User has typed in a filename and did not click cancel
saveFile = saveFileDialog1.FileName;
MessageBox.Show(saveFile);
saveCurrentState();
}
}
After having used these two filters with the respective fileDialogs, The expected results finally occurred. By default, when the user selects the save button and the savefiledialog shows up, the selected filetype is that of the Program X files type defined in the filter for the savefiledialog. Likewise the selected filetype for the openfiledialog is that of the Program X Files Type defined in the filter for the openfileDialog.
It would also be good to do some input validation as mentioned above in this thread. I just wanted to point out that the filters seem to be different between the two dialogs even though they both inherit the filedialog class.
//this must be ran as administrator due to the change of a registry key, but it does work...
private void doWork()
{
const string lm = "HKEY_LOCAL_MACHINE";
const string subkey = "\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\AutoComplete";
const string keyName = lm + subkey;
int result = (int)Microsoft.Win32.Registry.GetValue(keyName, "AutoComplete In File Dialog", -1);
MessageBox.Show(result.ToString());
if(result.ToString() == "-1")
{
//-1 means the key does not exist which means we must create one...
Microsoft.Win32.Registry.SetValue(keyName, "AutoComplete In File Dialog", 0);
OpenFileDialog ofd1 = new OpenFileDialog();
ofd1.ShowDialog();
}
if (result == 0)
{
//The Registry value is already Created and set to '0' and we dont need to do anything
}
}

Getting filesize from OpenFileDialog?

How can I get the filesize of the currently-selected file in my Openfiledialog?
You can't directly get it from the OpenFieldDialog.
You need to take the file path and consturct a new FileInfo object from it like this:
var fileInfo = new FileInfo(path);
And from the FileInto you can get the size of the file like this
fileInfo.Length
For more info look at this msdn page.
Without interop and like the first comment, once the dialogue has been complete i.e. file/s have been selected this would give the size.
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (openFileDialog1.Multiselect)
{
long total = 0;
foreach (string s in openFileDialog1.FileNames)
total += new FileInfo(s).Length;
MessageBox.Show(total.ToString());
}
else
{
MessageBox.Show(new FileInfo(openFileDialog1.FileName).Length.ToString());
}
}
}
File size during dialogue I feel would need to use interop
Andrew
I think there is 3 way, creating your custom open dialog or setting by code the view as detail or asking the user to use detail view
If you mean when the dialog is running, I suspect you just change the file view to details. However if you mean programmatically I suspect that you'd have to hook a windows message when the file is selected.

Categories