Unable to copy a file from one directory to application folder - c#

I am writing a c# desktop app where I want users to select a file from open file dialog after which the program will copy the file to where the application is executing from: here is my code that is not working at the moment
var dlg = new Microsoft.Win32.OpenFileDialog {
Title = "Select File",
DefaultExt = ".json",
Filter = "Json File (.json)|*.json",
CheckFileExists = true
};
if (dlg.ShowDialog() == true)
{
try
{
var currentDirectory = System.Windows.Forms.Application.ExecutablePath;
var destFile = Path.Combine(currentDirectory + "/temp/", dlg.FileName);
File.Copy(dlg.FileName, destFile, true);
}
catch (Exception ex)
{
MessageBox.Show(string.Format("An error occured: " + ex.Message));
}
}
Now I am getting the error that
the file is being used by another program
. When I edit the code that is meant to initiate the copy by removing true:
File.Copy(dlg.FileName, destFile);
I get the error that the
file already exists
in the directory where it is being selected from.

It seems, that you have an incorrect path to write into.
System.Windows.Forms.Application.ExecutablePath
returns exe file itself, not directory. Try
var destFile = Path.Combine(
Path.GetDirectoryName(Application.ExecutablePath), // Exe directory
"temp", // + Temp subdirectory
Path.GetFileName(dlg.FileName)); // dlg.FileName (without directory)
If you aren't sure that temp exists, you have to create it:
Directory.CreateDirectory(Path.GetDirectoryName(destFile));

Use below Code for Copy file from one folder to another folder.
string[] filePaths = Directory.GetFiles("Your Path");
foreach (var filename in filePaths)
{
string file = filename.ToString();
//Do your job with "file"
string str = "Your Destination"+file.ToString(),Replace("Your Path");
if (!File.Exists(str))
{
File.Copy(file , str);
}
}

Related

Extract zip file and overwrite (in the same directory - C#)

I'm starting some C# stuff, and i would like to extract and force to overwrite all files from a zip archive. I know that there are many other solution in Stack, but nothing works for me :/
i've tried this method:
try
{
string zipPath = (Directory.GetCurrentDirectory() + "\\" + "my_zip");
Console.WriteLine("Zip's path: " + zipPath);
string extractPath = Directory.GetCurrentDirectory();
ZipFile.ExtractToDirectory(zipPath, extractPath);
return (0); // 0 all fine
}
catch (Exception)
{
return (1); // 1 = extract error
}
This extractor works fine, but doesn't allow me to overwrite files meanwhile extraction, and it returns error and exceptions ... i've tried to take a look at MS-Documention, without success ...
someone know how does it work ?
Try something like this. Away from my dev box so this may require some tweaking, just writing it from memory.
Edit: As someone mentioned you can use ExtractToFile which has an overwrite option. ExtractToDirectory does not.
Essentially you unzip to a temporary folder then check if an unzipped file's name already exists in the destination folder. If so, it deletes the existing file and moves the newly unzipped one to the destination folder.
try
{
string zipPath = (Directory.GetCurrentDirectory() + "\\" + "my_zip");
Console.WriteLine("Zip's path: " + zipPath);
//Declare a temporary path to unzip your files
string tempPath = Path.Combine(Directory.GetCurrentDirectory(), "tempUnzip");
string extractPath = Directory.GetCurrentDirectory();
ZipFile.ExtractToDirectory(zipPath, tempPath);
//build an array of the unzipped files
string[] files = Directory.GetFiles(tempPath);
foreach (string file in files)
{
FileInfo f = new FileInfo(file);
//Check if the file exists already, if so delete it and then move the new file to the extract folder
if (File.Exists(Path.Combine(extractPath,f.Name)))
{
File.Delete(Path.Combine(extractPath, f.Name));
File.Move(f.FullName, Path.Combine(extractPath, f.Name));
}
else
{
File.Move(f.FullName, Path.Combine(extractPath, f.Name));
}
}
//Delete the temporary directory.
Directory.Delete(tempPath);
return (0); // 0 all fine
}
catch (Exception)
{
return (1); // 1 = extract error
}
Edit, in the event directories are unzipped (again, may need to be tweaked, I didn't test it):
try
{
string zipPath = (Directory.GetCurrentDirectory() + "\\" + "my_zip");
Console.WriteLine("Zip's path: " + zipPath);
//Declare a temporary path to unzip your files
string tempPath = Path.Combine(Directory.GetCurrentDirectory(), "tempUnzip");
string extractPath = Directory.GetCurrentDirectory();
ZipFile.ExtractToDirectory(zipPath, tempPath);
//build an array of the unzipped directories:
string[] folders = Directory.GetDirectories(tempPath);
foreach (string folder in folders)
{
DirectoryInfo d = new DirectoryInfo(folder);
//If the directory doesn't already exist in the destination folder, move it to the destination.
if (!Directory.Exists(Path.Combine(extractPath,d.Name)))
{
Directory.Move(d.FullName, Path.Combine(extractPath, d.Name));
continue;
}
//If directory does exist, iterate through the files updating duplicates.
else
{
string[] subFiles = Directory.GetFiles(d.FullName);
foreach (string subFile in subFiles)
{
FileInfo f = new FileInfo(subFile);
//Check if the file exists already, if so delete it and then move the new file to the extract folder
if (File.Exists(Path.Combine(extractPath, d.Name, f.Name)))
{
File.Delete(Path.Combine(extractPath, d.Name, f.Name));
File.Move(f.FullName, Path.Combine(extractPath, d.Name, f.Name));
}
else
{
File.Move(f.FullName, Path.Combine(extractPath, d.Name, f.Name));
}
}
}
}
//build an array of the unzipped files in the parent directory
string[] files = Directory.GetFiles(tempPath);
foreach (string file in files)
{
FileInfo f = new FileInfo(file);
//Check if the file exists already, if so delete it and then move the new file to the extract folder
if (File.Exists(Path.Combine(extractPath,f.Name)))
{
File.Delete(Path.Combine(extractPath, f.Name));
File.Move(f.FullName, Path.Combine(extractPath, f.Name));
}
else
{
File.Move(f.FullName, Path.Combine(extractPath, f.Name));
}
}
Directory.Delete(tempPath);
return (0); // 0 all fine
}

Copy files to C:\Program Files (x86)\ c# access denied when running application as administrator

I am creating an application that reads a .txt file with a list of files to copy to different locations and to overwrite the files if they already exist, one location is:
C:\Program Files (x86)\Common Files\System\ado\
When doing this I am getting the following error:
System.UnauthorizedAccessException: 'Access to the path 'C:\Program Files (x86)\Common Files\System\ado\msado27.tlb' is denied.
I am running my application as an Administrator and I have updated my applications manifest file to invoke the application as an Administrator user. However I am not sure why I am still getting this error even running as an Administrator?
To copy the files I am using the .Net file operations:
File.Copy(sourceFile, destFile, true);
Full code section that deals with the file copying for your reference:
void readFilesToInstall()
{
// 1 Read FileToInstall.txt Line By Line from C:\Temp2\BarsInstaller
// 2 each line read copy to correct location
// 3. update progress bar
string[] lines = File.ReadAllLines(#"C:\Temp2\BarsInstaller\FilesToInstall.txt");
string sourcePath = #"C:\Temp2\BarsInstaller\";
progressBar.Invoke((Action)delegate
{
progressBar.Maximum = lines.Length;
progressBar.Value = 0;
lblPercent.Text = "0%";
});
foreach (string line in lines)
{
string[] col = line.Split('=');
//process col[0], col[1], col[2]
string fileName = col[0];
//string sourceFullName = source + fileName;
DirectoryInfo fileCopyToLocation = new DirectoryInfo(col[1]);
string sourceFile = Path.Combine(sourcePath, fileName);
string destFile = Path.Combine(col[1], fileName);
darkLabel2.Invoke((Action)delegate
{
darkLabel2.Text = destFile;
darkLabel2.Refresh();
});
copyFilesToInstall(sourceFile, destFile, fileCopyToLocation);
progressBar.Invoke((Action)delegate
{
progressBar.Value++;
});
}
}
void copyFilesToInstall(string sourceFile, string destFile, DirectoryInfo target)
{
if(Directory.Exists(target.FullName) == false)
{
Directory.CreateDirectory(target.FullName);
}
File.Copy(sourceFile, destFile, true);
}

importing from local directory

I am having difficulties importing from project directory. Here is my code:
FileDialog file = new OpenFileDialog();
file.InitialDirectory = #"";
file.Filter = "txt files (*.txt)|*.txt";
file.RestoreDirectory = true;
if (file.ShowDialog() == DialogResult.OK && this.mAT != null)
{
if (file.FileName != String.Empty || file.FileName != null)
return this.mAT.importFromLexiconFile(file.FileName);
}
else return false;
return false;
How can I import a file from a local directory using a directory as a text like something.txt instead of looking for the file in FileDialog?
You can get the directory from where the project was started using:
Environment.CurrentDirectory;
Or you can get the location that your .exe is located in using:
Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
At runtime, this would be something like:
C:\projects\myapplication\myproject\bin\Debug\
Here's how you can find your file, and some different things you can do with it. Not sure exactly what you want to do:
private static void Main()
{
// The directory to search for the file
var searchPath = Path.GetDirectoryName(
System.Reflection.Assembly.GetEntryAssembly().Location);
// The name of the file we're searching for
var fileName = "MyFile.txt";
// Get the first match
var theFile = Directory.GetFiles(searchPath, fileName).FirstOrDefault();
// If the match is not null, we found the file
if (theFile != null)
{
// Output some information about the file
Console.WriteLine("Found the file: {0}", fileName);
Console.WriteLine("The full path of the file is: {0}", theFile);
// If it's a text file, here's one way to get the contents
var fileContents = File.ReadAllText(theFile);
Console.WriteLine("The contents of the file are:{0}{1}", Environment.NewLine,
fileContents);
// If you need detailed info about the file, or
// want to write to it, create a FileInfo object
var fileInfo = new FileInfo(theFile);
// Output some detailed information about the file
Console.WriteLine("The file was created on: {0}", fileInfo.CreationTime);
Console.WriteLine("The file was last modified on: {0}",
fileInfo.LastWriteTime);
Console.WriteLine("The file attributes are:");
Console.WriteLine(" - ReadOnly: {0}",
Convert.ToBoolean(fileInfo.Attributes & FileAttributes.ReadOnly));
Console.WriteLine(" - Hidden: {0}",
Convert.ToBoolean(fileInfo.Attributes & FileAttributes.Hidden));
Console.WriteLine(" - System: {0}",
Convert.ToBoolean(fileInfo.Attributes & FileAttributes.System));
}
}

How can I save Image files in in my project folder?

In my Windows application, I have a PictureBox and a Button control. I want to load an Image file from user from the button's OnClick event and save that image file in a folder name "proImg" which is in my project. Then I want to show that image in the PictureBox.
I have written this code, but it is not working:
OpenFileDialog opFile = new OpenFileDialog();
opFile.Title = "Select a Image";
opFile.Filter = "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*";
if (opFile.ShowDialog() == DialogResult.OK)
{
try
{
string iName = opFile.FileName;
string filepath = "~/images/" + opFile.FileName;
File.Copy(iName,Path.Combine("~\\ProImages\\", Path.GetFileName(iName)));
picProduct.Image = new Bitmap(opFile.OpenFile());
}
catch (Exception exp)
{
MessageBox.Show("Unable to open file " + exp.Message);
}
}
else
{
opFile.Dispose();
}
It's not able to save the image in the "proImg" folder.
Actually the string iName = opFile.FileName; is not giving you the full path. You must use the SafeFileName instead. I assumed that you want your folder on your exe directory also. Please refer to my modifications:
OpenFileDialog opFile = new OpenFileDialog();
opFile.Title = "Select a Image";
opFile.Filter = "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*";
string appPath = Path.GetDirectoryName(Application.ExecutablePath) + #"\ProImages\"; // <---
if (Directory.Exists(appPath) == false) // <---
{ // <---
Directory.CreateDirectory(appPath); // <---
} // <---
if (opFile.ShowDialog() == DialogResult.OK)
{
try
{
string iName = opFile.SafeFileName; // <---
string filepath = opFile.FileName; // <---
File.Copy(filepath, appPath + iName); // <---
picProduct.Image = new Bitmap(opFile.OpenFile());
}
catch (Exception exp)
{
MessageBox.Show("Unable to open file " + exp.Message);
}
}
else
{
opFile.Dispose();
}
You should provide a correct destination Path to File.Copy method. "~\ProImages..." is not a correct path. This example will copy selected picture to folder ProImages inside the project's bin folder :
string iName = opFile.FileName;
File.Copy(iName, Path.Combine(#"ProImages\", Path.GetFileName(iName)));
the path is relative to current executable file's location, except you provide full path (i.e. #"D:\ProImages").
In case you didn't create the folder manually and want the program generate ProImages folder if it doesn't exist yet :
string iName = opFile.FileName;
string folder = #"ProImages\";
var path = Path.Combine(folder, Path.GetFileName(iName))
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
File.Copy(iName, path);
PS: Notice the use of verbatim (#) to automatically escape backslash (\) characters in string. It is common practice to use verbatim when declaring string that represent path.
Try using picturebox.Image.Save function. In my program it is working
PictureBox.Image.Save(Your directory, ImageFormat.Jpeg)
example
pictureBox2.Image.Save(#"D:/CameraImge/"+foldername+"/"+ numbering + ".jpg", ImageFormat.Jpeg);
You write code like this.
string appPath = Path.GetDirectoryName(Application.ExecutablePath) +foldername ;
pictureBox1.Image.Save(appPath + #"\" + filename + ".jpg", ImageFormat.Jpeg);

Could not find a part of the path

I am getting " Could not find a part of the path" error while copying a file from server to local machine. here is my code sample:
try
{
string serverfile = #"E:\installer.msi";
string localFile = Path.GetTempPath();
FileInfo fileInfo = new FileInfo(serverfile);
fileInfo.CopyTo(localFile);
return true;
}
catch (Exception ex)
{
return false;
}
Can anyone tell me what's wrong with my code.
Path.GetTempPath
is returning you folder path. you need to specify file path as well. You can do it like this
string tempPath = Path.GetTempPath();
string serverfile = #"E:\installer.msi";
string path = Path.Combine(tempPath, Path.GetFileName(serverfile));
File.Copy(serverfile, path); //you can use the overload to specify do you want to overwrite or not
You should copy file to file, not file to directory:
...
string serverfile = #"E:\installer.msi";
string localFile = Path.GetTempPath();
FileInfo fileInfo = new FileInfo(serverfile);
// Copy to localFile (which is TempPath) + installer.msi
fileInfo.CopyTo(Path.Combine(localFile, Path.GetFileName(serverfile)));
...

Categories

Resources