Directory Not Found Exception C# - c#

I am creating the file list of both source & target directory in target location, the requirement is based on the difference of these two files copy only the files that are new from last iteration.
For 1st iteration copy works, next iteration creates a blank diff [Difference] file is created, to handle this I have added if condition where I check length of file and copy them again. But the if condition is not working as per behavior, with length zero it goes to else statement and throws out error with blank file name :
Could not find a part of the path 'C:\interswitch\source\'.
Here's the code:
string path = Path.Combine(target_dir, "Diff.txt");
if (new FileInfo(path).Length == 0)
{
foreach (FileInfo fi in sourceinfo.GetFiles())
{
fi.CopyTo(Path.Combine(targetinfo.ToString(), fi.Name), true);
}
}
else
foreach (string file in File.ReadLines(path))
{
{
string sourceFile = System.IO.Path.Combine(source_dir, file);
string destFile = System.IO.Path.Combine(target_dir, file);
System.IO.File.Copy(sourceFile, destFile, true);
}
}

if (new FileInfo(path).Length == 0)
does not produce 0 apparently, you have to fix that

Related

How can you copy a file and paste it from one location(directory) to another location (directory) in C#? [duplicate]

This question already has answers here:
copy files from one location to another
(4 answers)
Closed 8 months ago.
I want to know how to copy a file, not regarding it's type, pptx docx txt, and paste it in another address of the directory in C#. I assume that the File.Copy function is only available for .txt file, and it is not a file copy and paste, it is a contents copy and paste.
Thank you.
This code is from the Microsoft docs, apparently it can copy .jpg files and if it can it should be able to copy all file types
string sourceDir = #"c:\current";
string backupDir = #"c:\archives\2008";
try
{
string[] picList = Directory.GetFiles(sourceDir, "*.jpg");
string[] txtList = Directory.GetFiles(sourceDir, "*.txt");
// Copy picture files.
foreach (string f in picList)
{
// Remove path from the file name.
string fName = f.Substring(sourceDir.Length + 1);
// Use the Path.Combine method to safely append the file name to the path.
// Will overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true);
}
// Copy text files.
foreach (string f in txtList)
{
// Remove path from the file name.
string fName = f.Substring(sourceDir.Length + 1);
try
{
// Will not overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
}
// Catch exception if the file was already copied.
catch (IOException copyError)
{
Console.WriteLine(copyError.Message);
}
}
// Delete source files that were copied.
foreach (string f in txtList)
{
File.Delete(f);
}
foreach (string f in picList)
{
File.Delete(f);
}
}
catch (DirectoryNotFoundException dirNotFound)
{
Console.WriteLine(dirNotFound.Message);
}
Source: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.copy?view=net-6.0#system-io-file-copy(system-string-system-string-system-boolean)

C# move file with 2 mapped drives

I need to move a file existing on a mapped folder named A:\ to another mapped folder B:\ using the code below
File.Move(#"A:\file.txt",#"B:\");
it return the error below
Could not find file 'A:\file.txt'.
i tried to open A:\file.txt in folder explorer and it open the file normally
It looks like File.Move only works for files on local drives.
File.Move actually invokes MoveFile which states that both source and destination should be:
The current name of the file or directory on the local computer.
You would be better by using a combination of File.Copy and File.Delete.
Copy the file from A to B, then delete the file from A.
As stated before, File.Move needs sourceFileName and destFileName.
And you are missing the Filename in the second parameter.
If you want to move you file and keep the same name you can Extract the File name from the sourceFileName with GetFileName and use it in your destFileName
string sourceFileName = #"V:\Nothing.txt";
string destPath = #"T:\";
var fileName = Path.GetFileName(sourceFileName);
File.Move(sourceFileName, destPath + fileName );
Here is a debug code:
public static void Main()
{
string path = #"c:\temp\MyTest.txt";
string path2 = #"c:\temp2\MyTest.txt";
try
{
if (!File.Exists(path))
{
// This statement ensures that the file is created,
// but the handle is not kept.
Console.WriteLine("The original file does not exists, let's Create it.");
using (FileStream fs = File.Create(path)) {}
}
// Ensure that the target does not exist.
if (File.Exists(path2)) {
Console.WriteLine("The target file already exists, let's Delete it.");
File.Delete(path2);
}
// Move the file.
File.Move(path, path2);
Console.WriteLine("{0} was moved to {1}.", path, path2);
// See if the original exists now.
if (File.Exists(path))
{
Console.WriteLine("The original file still exists, which is unexpected.");
}
else
{
Console.WriteLine("The original file no longer exists, which is expected.");
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}

Saving multiple images using File.WriteAllBytes saves only the last one

i'm trying to save multiple images with File.WriteAllBytes(), even after i tried to seperate between the saves with 'Thread.Sleep()' it's not working..
my code:
byte[] signatureBytes = Convert.FromBase64String(model.Signature);
byte[] idBytes = Convert.FromBase64String(model.IdCapture);
//Saving the images as PNG extension.
FileManager.SaveFile(signatureBytes, dirName, directoryPath, signatureFileName);
FileManager.SaveFile(idBytes, dirName, directoryPath, captureFileName);
SaveFile Function:
public static void SaveFile(byte[] imageBytes, string dirName, string path, string fileName, string fileExt = "jpg")
{
if (!string.IsNullOrEmpty(dirName)
&& !string.IsNullOrEmpty(path)
&& !string.IsNullOrEmpty(fileName)
&& imageBytes.Length > 0)
{
var dirPath = Path.Combine(path, dirName);
var di = new DirectoryInfo(dirPath);
if (!di.Exists)
di.Create();
if (di.Exists)
{
File.WriteAllBytes(dirPath + $#"\{fileName}.{fileExt}", imageBytes);
}
}
else
throw new Exception("File cannot be created, one of the parameters are null or empty.");
}
File.WriteAllBytes():
"Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten"
As expecify in :
https://msdn.microsoft.com/en-ca/library/system.io.file.writeallbytes(v=vs.110).aspx
So if you can only see the last one, you are overwriting the file.
Apart from the possibility (as mentioned by #Daniel) that you're overwriting the same file, I'm not sure about this code:
var di = new DirectoryInfo(dirPath);
if (!di.Exists)
di.Create();
if (di.Exists)
{
...
}
I'd be surprised if, having called di.Create(), the Exists property is updated. In fact, it is not updated - I checked.
So, if the directory did not exist, then you won't enter the conditional part even after creating the directory. Could that explain your issue?

Directory.Getfiles() reads only the first file in the folder

HI I need to read all the files in a directory. The code below reads only the first file even if 10 files are present in the folder. It does not throw any exception. Why is it not printing the other files name? Any help appreciated.
string[] txtFiles = Directory.GetFiles(#"D:\Sample", "*.txt");
foreach (string item in txtFiles)
{
string contents = File.ReadAllText(item);
if (contents.Contains("testing"))
{
Console.WriteLine(item);
}
}
In D:\Sample I have 10 sample files which contain the word testing in them. But it reads only Sample1.txt and does not read the rest.
Output:
Sample1.txt
Please change you File variable as file as below and try.
string[] array = Directory.GetFiles(#"D:\Sample", "*.txt");
foreach (string file in array)
{
Application.DoEvents();
string contents = File.ReadAllText(file);
if (contents.Contains("testing"))
{
Console.WriteLine(file);
}
}

c# copying files from source folder to target folder

Source and Target have the same subdirectories like this :
c:\fs\source\a\
c:\fs\source\b\
c:\fs\target\a\
c:\fs\target\b\
I am battling with copying files from source to target if not existing files. What is the best way in C# to compare source folders with target folders - check if target files dont exit, copy files from a specific source (c:\fs\source\a\config.xml and app.config) to a specific target (c:\fs\target\a\). If target files exist, ignore it. How to write it in C#?
Your code example very much appreciated. Thanks!
public void TargetFileCreate()
{
foreach (var folder in SourceFolders)
{
string[] _sourceFileEntries = Directory.GetFiles(folder);
foreach (var fileName in _sourceFileEntries)
{ //dont know how to implement here:
//how to compare source file to target file to check if files exist or not
//c:\fs\source\A\config.xml compares to c:\fs\target\A\ (no files) that should be pasted
//c:\fs\source\B\config.xml compares to c:\fs\target\B\config.xml that is already existed - no paste
}
}
}
foreach (var file in Directory.GetFiles(source))
{
File.Copy(file, Path.Combine(target, Path.GetFileName(file)), false);
}
You can check for each file if it exists this way:
string curFile = #"c:\temp\test.txt";
Console.WriteLine(File.Exists(curFile) ? "File exists." : "File does not exist.");
put this inside your loop. then copy those files there.
MSDN CODE:
// Simple synchronous file copy operations with no user interface.
// To run this sample, first create the following directories and files:
// C:\Users\Public\TestFolder
// C:\Users\Public\TestFolder\test.txt
// C:\Users\Public\TestFolder\SubDir\test.txt
public class SimpleFileCopy
{
static void Main()
{
string fileName = "test.txt";
string sourcePath = #"C:\Users\Public\TestFolder";
string targetPath = #"C:\Users\Public\TestFolder\SubDir";
// Use Path class to manipulate file and directory paths.
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
// To copy a file to another location and
// overwrite the destination file if it already exists.
System.IO.File.Copy(sourceFile, destFile, true);
// To copy all the files in one directory to another directory.
// Get the files in the source folder. (To recursively iterate through
// all subfolders under the current directory, see
// "How to: Iterate Through a Directory Tree.")
// Note: Check for target path was performed previously
// in this code example.
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(s, destFile, true);
}
}
else
{
Console.WriteLine("Source path does not exist!");
}
// Keep console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
foreach (var file in Directory.GetFiles(source))
{
var targetFile = System.IO.Path.Combine(target, System.IO.Path.GetFileName(file));
if(!File.Exists(targetFile))
{
File.Copy(file, targetFile)
}
}

Categories