File.Copy - DirectoryNotFoundException was unhandled - c#

When I use this code it doesn't throw any errors but it still doesn't copy anything. Any ideas?.
//string spath = string.Format("S:\\ 0A36303 / user:admin");
DateTime theDate = dateTimePicker1.Value.Date;
DirectoryInfo Dir = new DirectoryInfo("S:");
string dircreate = string.Format(#"N:\{0:MM-dd-yyyy}\" + label1.Text + "LogFiles", dateTimePicker1.Value.Date, label1.Text);
DirectoryInfo target = new DirectoryInfo(dircreate);
FileInfo[] fis = Dir.GetFiles( ".txt", SearchOption.AllDirectories);
foreach (FileInfo fi in fis)
{
if (fi.LastWriteTime.Date == theDate)
{
File.Copy(fi.FullName, target.FullName + #"\" + fi.Name, true);
}
}
}
}
}

Try using the full UNC path to access the file:
DirectoryInfo Dir = new DirectoryInfo(#"\\server\\share\\pathtofile");

Two possible problems come to mind:
The S:\PC.log file doesn't exist => you cannot copy non-existent file
The process you are executing your code under doesn't have read permission to the specified folder (S:). Looks like a network share. If you are running this code inside an ASP.NET application the process probably doesn't have read permissions to this remote share => you cannot copy a file that you don't have permissions to access.

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 containing a name from source to destination c#

I have a list of Strings with a series of names, I want to find these names in the source directory and copy them to the destination.
This is what I am trying but with this I copy all source directory in target directory:
List<string> ncs = new List<string>();
ncs = getNames();
foreach (var file in Directory.GetFiles(sourceDir))
File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file)));
foreach (var directory in Directory.GetDirectories(sourceDir))
CopyNCfromTo(directory, Path.Combine(targetDir, Path.GetFileName(directory)));
I am trying in this way too:
List<string> ncs = new List<string>();
ncs = getNames();
for (int i = 0; i < ncs.Count; i++)
{
FileInfo[] filesInDir = hdDirectoryInWhichToSearch.GetFiles(ncs[i].ToString());
}
I thought to loop the list and the look for every file in the source folder, how could I do this?
I assume that the ncs list containing only names not the file path or the file name with extension.
foreach (var file in Directory.GetFiles(sourceDir))
if (ncs.Contains(Path.GetFileName(file).Split('.').First()))
File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file)));
This is happening because foreach is browsing the files contained in the folder and not the list of names, that way, all files are copied to the destination folder.
foreach(string fileName in ncs){
string path = sourceDir + fileName;
bool result = System.IO.File.Exists(path);
if(result == true){
string destinationPath = targetDir + fileName;
System.IO.File.Copy(path,destinationPath);
}
}
That way you go through the list of names and check if the file exists, if it exists, copy the file to the destination folder
You can iterate over ncs, build the source and destination paths, and do a copy if the file exists.
Caveat: File.Exists() can introduce a race condition. If you are not confident no other process is working in that folder then you should handle IO exceptions.
string sourceDir = "C:\\....";
string targetDir = "C:\\....";
foreach (string filename in ncs)
{
string srcFile = Path.Combine(sourceDir, filename);
string destFile = Path.Combine(targetDir, filename);
if (File.Exists(srcFile))
{
File.Copy(srcFile, destFile);
}
}

Unable to copy a file from one directory to application folder

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);
}
}

Check Zip File content and extract

Hi I want to extract a ZipFile that has various of text files. But i could be that de text files are in a folder. So what i want to do is: If an folder exists just exract normaly if not create a folder with name of ZipFile. The reason is i don't want to have a folder in a folder with the same name.
My Previous Code:
foreach (string file in newZips) {
FileInfo fileInfo = new FileInfo(file);
string dirName = newPath + "\\" + fileInfo.Name.Substring(0, fileInfo.Name.Length - 4);
Console.WriteLine(dirName);
Directory.CreateDirectory(dirName);
ZipFile.ExtractToDirectory(allZipsPath + "\\" + fileInfo.Name, dirName);
}
Maybe this helps you:
string path = #"C:\..\..\myFolder";
if(!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
Thats how you can check a path if it contains the Folder you expect. And if not it creates that Folder!
--- EDIT (if unknown zip-Name) ---
string myPathToZip = #"C:\..\..\folderName";
foreach (string file in Directory.GetFiles(myPathToZip, "*.zip", SearchOption.AllDirectories))
{
//the current path of the zipFile (with the Name included)
var path = new FileInfo(file.ToString());
//The filename
var filename = Path.GetFileName(file.ToString()).Replace(".zip", "");
}

C# File.Move won't find existing file?

I have a method that unzips files into an 'unzipped' files folder. Problem is that there are files duplicated in two zip files - so when the second zip file is extracted the process fails as the file name already exists. I decided to rename the existing file to avoid this problem, but my if(File.Exists...) statement is not picking up files that exist. This is probably a noob syntax issue?
private void UnzipFiles()
{
sourceDirectory = #"c:\id";
unzippedDirectory = #"C:\id\z_unzipped";
processedDirectory = #"C:\id\z_processed";
// get list of files from directory and unzip them
DirectoryInfo dirInfo = new DirectoryInfo(sourceDirectory);
FileInfo[] infos = dirInfo.GetFiles("*.zip");
foreach (FileInfo f in infos)
{
if (File.Exists(unzippedDirectory + #"\" + f.Name)){
// rename existing file
File.Move(unzippedDirectory + #"\" + f.Name, unzippedDirectory + #"\" + f.Name + " renamed by " + f.Name);
}
System.IO.Compression.ZipFile.ExtractToDirectory(f.FullName, unzippedDirectory);
File.Move(f.FullName, processedDirectory + #"\" + f.Name);
}
}

Categories

Resources