File Copy in C#.Net - c#

I'm trying to build a copier so that you use the openFileDialog to chose a file and then the folderBrowserDialog to choose the location to copy it to.
The problem I'm having is that when I use File.Copy(copyFrom,copyTo) it gives me an exception that I can't copy to a directory.
Is there anyway around this, or am I just missing something stupid and noobish. I've tryed useing openFD for choosing both locations and have just tried using the folderBD to see if it made a difference.
I know there should be if statements there to catch the exceptions but this is a rough draft of the code to get working 1st.
Thanks in advance for the help, code attached.
// Declare for use in all methods
public string copyFrom;
public string copyTo;
public string rootFolder = #"C:\Documents and Settings\cmolloy\My Documents";
private void btnCopyFrom_Click(object sender, EventArgs e)
{
// uses a openFileDialog, openFD, to chose the file to copy
copyFrom = "";
openFD.InitialDirectory = rootFolder;
openFD.FileName = "";
openFD.ShowDialog();
// sets copyFrom = to the file chosen from the openFD
copyFrom = openFD.FileName;
// shows it in a textbox
txtCopyFrom.Text = copyFrom;
}
private void btnCopyTo_Click(object sender, EventArgs e)
{
//uses folderBrowserDialog, folderBD, to chose the folder to copy to
copyTo = "";
this.folderBD.RootFolder = System.Environment.SpecialFolder.MyDocuments;
this.folderBD.ShowNewFolderButton = false;
folderBD.ShowDialog();
DialogResult result = this.folderBD.ShowDialog();
// sets copyTo = to the folder chosen from folderBD
copyTo = this.folderBD.SelectedPath;
//shows it in a textbox.
txtCopyTo.Text = copyTo;
}
private void btnCopy_Click(object sender, EventArgs e)
{
// copys file
File.Copy(copyFrom, copyTo);
MessageBox.Show("File Copied");

You have to append the file name to the directory path. Do this:
string destinationPath = Path.Combine(copyTo, Path.GetFileName(copyFrom));
File.Copy(copyFrom, destinationPath);
(with this you'll copy selected file to another directory with the same name of the original one and it'll throw an exception if the same file already exist in that directory)
Edit
Side note: do not hard code the path in your source code, use this:
rootFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
to get the path of current user's documents folder.

Do this:
File.Copy(copyFrom, Path.Combine(copyTo, Path.GetFileName(copyFrom)));

File.Copy needs to know the full path of the new file you want, including the file name. If you just want to use the same file name, you can use this to append the file name to the path:
copyTo = Path.Combine(copyTo, Path.GetFileName(copyFrom));

Related

How to search for a file extension (.xls) and change it's name? C#

The product I'm using is a Beijer HMI, currently i can generate a report and save it to a known location (my desktop - C:\Users\mrdav\Desktop).
I need to be able to search on my desktop for a file extension .xls and change its name.
When the report is generated by the HMI, it uses the date and time which means when the file is generated the name will be different every time.
On the press of a button i need to search my desktop for the .xls file and change its name to a variable.
// This is my variable with my program
string NewName = Globals.Tags.Tag1.Value;
The code that is generated needs to sit within the below example.
public partial class Screen1
{
void Button1_Click(System.Object sender, System.EventArgs e)
{
// Code to be added here...
}
}
Hopefully someone can help, I’m using windows compact framework so limited on functionality.
Any questions please let me know.
Thanks in advance,
Dave
Here is an example how you can do that:
DirectoryInfo dir = new DirectoryInfo(sExportPath);
FileInfo[] Files = dir.GetFiles("*.csv");
foreach(FileInfo file in Files )
{
// rename file
System.IO.File.Move(file.FullName, GenerateNewFileName());
}
//elsewhere in the class
private string GenerateNewFileName()
{
//here is where you implement creating or getting the filename that you want your file to be renamed to. An example might look like the below
string serialNumber = GetSerialNumber(); //Get the serial number that you talked about in the question. I've made it a string, but it could be an int (it should be a string)
return Path.ChangeExtension(serialNumber,".xls"); //to use path you will need a using statement at the top of your class file 'using System.IO'
}
This seems to work...but i know its not as tidy as it could be.
Any suggestions?
Thanks to all that helped, got there in the end!
void Button_Click(System.Object sender, System.EventArgs e)
{
try
{
// Location for new file
string NewFileName = #"c:\users\mrdav\desktop\testfolder\";
// Add varibale name to new file
NewFileName += Globals.Tags.Tag1.Value;
// add .xls extention to new file
NewFileName += ".xls";
//show new file name to check all ok
MessageBox.Show (NewFileName);
//search for .xls in known directory
DirectoryInfo di = new DirectoryInfo(#"c:\users\mrdav\desktop");
FileInfo[] Files = di.GetFiles("*.xls");
// if files exist with .xls extention
foreach(FileInfo file in Files )
{
// show full file name
MessageBox.Show (file.FullName);
//rename old file to new file name and move to new folder
File.Move(file.FullName, NewFileName);
}
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}

How to find and copy .pdf file to clipboard

I'm trying to copy a pdf file to the clipboard so I can later paste it by Ctrl+V.
The following code can find a file but I'm not sure how to copy it to the clipboard.
How can I copy a pdf file once it is found?
private void copyToClipbard_Click(object sender, RoutedEventArgs e)
{
var file = Directory.GetFiles(#"C:\MyFolder\", "myPDFFile.pdf", SearchOption.AllDirectories).FirstOrDefault();
Clipboard.SetDataObject(file);
}
I get error:
An unhandled exception of type 'System.ArgumentNullException' occurred in PresentationCore.dll
EDIT: I also tried the following, I don't get any errors but it doesn't copy the file.
EDIT: The following code does work, I was not putting the right path, I like jasttims answer better though.
private void copyToClipbard_Click(object sender, RoutedEventArgs e)
{
var file = Directory.GetFiles(#"C:\MyFolder\", "myPDFFile.pdf", SearchOption.AllDirectories).FirstOrDefault();
var dataObj = new DataObject();
string[] fileName = new string[1];
fileName[0] = file;
dataObj.SetData(DataFormats.FileDrop, fileName, true);
Clipboard.SetDataObject(dataObj, true);
}
Try using the "Clipboard" class.
It features all the methods necessary for putting data on the Windows clipboard.
StringCollection paths = new StringCollection();
paths.Add("c:\file.pdf");
Clipboard.SetFileDropList(paths);

Getting File path from a open file dialog

I want to make a button that
opens a file from some location in file system,
gets its file path,
pass the file path like an argument to a method
open that file and do something with it.
I've made a button like this:
private void button1_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog fDialog = new OpenFileDialog();
fDialog.Title = "Open XML file";
fDialog.Filter = "XML files|*.config";
fDialog.InitialDirectory = #"C:\";
fDialog.ShowDialog();
}
I already made a method that reads from hard-coded location, but can someone help me about that file path part variable?
Method reads file with XmlTextReader like this:
private void ReadAdvancedConfigFile()
{
XElement root = null;
root = XElement.Load(new XmlTextReader(#"C:\Users\nemanja.mosorinski\Downloads\__Research-master\__Research-master\SEDMSVSPackage\VisualStudioPackage\AppRes\ConfigFiles\Unity.config"));
}
So basically I want to put new file path for some file founded by OpenFileDialog in root variable.
Change this line:
fDialog.ShowDialog();
To:
bool? control = fDialog.ShowDialog();
if(control.Value)
{
var filePath = fDialog.FileName;
ReadAdvancedConfigFile(filePath)
}
Also you should change the method signature
private void ReadAdvancedConfigFile(string path)

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

File System Entries Browser Dialog c#

I'm usin Windows.Forms aplication and I can get files or directory from my user using OpenFileDialog or FolderBrowserDialog. But I need get both in a unique dialog. I Try use OpenFileDialog with .multselect = true and select files and folders, but in code when I acess OpenFileDialog.FileNames this property returns only a file names, never a selected directory.
Exists a static method in System.IO.Directory call GetFileSystemEntries that do exactly I want. But I need a Dialog that do it.
Anyone can help me?
It is not possible to get folder and files with inly a single
dialog().
According to microsoft's documentation about c# You have to use different dialog to select folder and files
try :
string baseFolder = System.IO.Directory.GetParent(strToFile).ToString();
This will give you the folder name of the file.
or use FileInfo!
FileInfo fi = new FileInfo(strToFile);
string fileFolder = fi.DirectoryName;
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string[] files = openFileDialog1.FileNames;
if (files != null && files.Length > 0)
{
// returns the root directory
string folder = System.IO.Path.GetDirectoryName(files[0]);
// Obtain the file system entries in the directory path.
string[] directoryEntries =
System.IO.Directory.GetFileSystemEntries(folder);
}
}
}

Categories

Resources