I have a code to create new folder and move file to that folder using FileSystemWatcher.But it gives following error.
System.IO.IOException: The process cannot access the file because it
is being us ed by another process. at
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.__Error.WinIOError() at System.IO.File.Move(String
sourceFileName, String destFileName) at
FolderWatcher.Program.ProcessRenewalFolder(Object sender,
FileSystemEventA rgs e)
Following is the code
'private static void ProcessRenewalFolder(object sender, FileSystemEventArgs e)
{
Console.WriteLine("Renewal Received.... ");
DirectoryInfo d = new DirectoryInfo(#"E:\SCN_DOCS\RENEWAL\");
DirectoryInfo dest = new DirectoryInfo(#"E:\QUEUED_SCN_DOCS\RENEWAL\");
if (!d.Exists)
{
return;
}
FileInfo[] Files = d.GetFiles("*.pdf");
string jobNo = "";
string branchCode = "";
foreach (FileInfo file in Files)
{
jobNo = file.Name;
DirectoryInfo newDir = null;
if (!Directory.Exists(dest.FullName + jobNo.ToUpper()))
{
System.IO.Directory.CreateDirectory(dest.FullName + jobNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper());
}
Console.WriteLine(jobNo + " - " + branchCode);
try
{
File.Move(file.FullName, dest.FullName + jobNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper() + "\\" + file.Name.ToUpper());
UpdateRenewal(jobNo.Substring(0, file.Name.LastIndexOf(".")).ToUpper());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}'
Please let me know the reason for this...
in below folder path
DirectoryInfo d = new DirectoryInfo(#"E:\SCN_DOCS\RENEWAL\")
any new file created using your c# application if yes than you need to dispose the object of newly created file for example
Bitmap bitmap = new Bitmap();
// your Image file creation code...
bitmap.Dispose();
as per your question you are working with .pdf file so if you created any new pdf file in above folder just before moving file, than you need to dispose that object of newly created pdf file.
see this answer https://stackoverflow.com/a/31830176/4988990
It can happen if the file is still open in the program that generated the PDF (i.e. the program that put it in the folder).
When you work with a directory watcher I suggest that you:
Put all watched files in some sort of a list.
Use a Timer and process files that have been in the list for X seconds.
If the file can't be accessed, put it in the end of the list.
In that way you get a more forgiving solution and it's not likely that you'll miss files due to errors.
Related
I have a folder that contains many png images in my resources of my WPF application. I would like to add this folder to appdata/roaming. Since there are many images that are sorted in folders, I would prefer to add the whole folder. Is there any way to do this?
By the way, the folder is in a directory called Resources and all the pngs are build as resources in Visual Studio.
Here is my code example for your question:
public void MyCopy()
{
//1.You can use the following code to get the path appdata/roaming, and suppose you want to copy the files to NewImageFolder
string strTarget = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString() + "\\NewImageFolder\\";
if (!Directory.Exists(strTarget))
{
Directory.CreateDirectory(strTarget);
}
//2. Then you need to get the path of your the File to be copied
string strSource = AppDomain.CurrentDomain.BaseDirectory;
strSource = strSource.Substring(0, strSource.LastIndexOf("bin")) + "Resources\\Image";
//3.Copy the file
DirectoryInfo dir = new DirectoryInfo(strSource);
FileInfo[] files = dir.GetFiles();
string strFileName = null;
foreach (FileInfo file in files)
{
strFileName = strSource + "\\" + file.Name;
File.Copy(strFileName, System.IO.Path.Combine(strTarget, System.IO.Path.GetFileName(strFileName)));
}
}
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());
}
}
I have no problems when I want to create a new folder
I'm working with
Directory.CreateDirectory
Now I'm trying to get all image files from my desktop and I want to move all images to that folder which was created with Directory.CreateDirectory
I've testet file.MoveTo
from here
FileInfo file = new FileInfo(#"C:\Users\User\Desktop\test.txt");
to here
file.MoveTo(#"C:\Users\User\Desktop\folder\test.txt");
This works perfect.
Now I want to do that with all the image files from my dekstop
(Directory.CreateDirectory(#"C:\Users\User\Desktop\Images");)
How could I do that?
Example code of getting images with certain extentions from one root folder:
static void Main(string[] args)
{
// path to desktop
var desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
//get file extentions by speciging the needed extentions
var images = GetFilesByExtensions(new DirectoryInfo(desktopPath) ,".png", ".jpg", ".gif");
// loop thrue the found images and it will copy it to a folder (make sure the folder exists otherwise filenot found exception)
foreach (var image in images)
{
// if you want to move it to another directory without creating a copy use:
image.MoveTo(desktopPath + "\\folder\\" + image.Name);
// if you want to move a copy of the image use this
File.Copy(desktopPath + "\\"+ image.Name, desktopPath + "\\folder\\" + image.Name, true);
}
}
public static IEnumerable<FileInfo> GetFilesByExtensions(DirectoryInfo dir, params string[] extensions)
{
if (extensions == null)
throw new ArgumentNullException("extensions");
var files = dir.EnumerateFiles();
return files.Where(f => extensions.Contains(f.Extension));
}
Please try this:
You can filter files in a specific directory and then looop through search results to move each file, you might be able to modify search pattern to match on a number of different image file formats
var files = Directory.GetFiles("PathToDirectory", "*.jpg");
foreach (var fileFound in files)
{
//Move your files one by one here
FileInfo file = new FileInfo(fileFound);
file.MoveTo(#"C:\Users\User\Desktop\folder\" + file.Name);
}
De
I have to copy folders and files from one network folder to other. There are some files which cannot be copied since it is named with special characters.
There are so many folders and sub-folders with 3 GB of data. To avoid this problem, I want to write a C# program which can copy all folders, sub-folders and files
with a log file(notepad). Log file which should note the non-copying file details and its path so that easy to trace them further. Can anybody please help me quickly
by providing a c# program or at-least a reference. A console or Win-form application, I am using Visual studio 2010 and Windows 7
copying like below
Copy form :- https://ap.sharepoint.a5-group.com/cm/Shared Documents/IRD/EA
To :- https://cr.sp.a5-group.com/sites/cm/Shared Documents/IRD/EA
here, try this:
Edit: my answer works for local Network Directories, I didn't mention, that you want to copy directiories from HTTPS, for that you have to use WebClient with Credentials
class DirectoryCopyExample
{
string pathFrom = "C:\\someFolder";
string pathTo = "D:\\otherFolder";
string LogText = string.Empty;
static void Main()
{
// Copy from the current directory, include subdirectories.
DirectoryCopy(pathFrom, pathTo, true);
}
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
try
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
catch(Exception)
{
//Write Files to Log whicht couldn't be copy
LogText += DateTime.Now.ToString() + ": " + file.FullName;
}
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
}
at the end you have to save the variable LogTex to the file, or whatever you need
source: http://msdn.microsoft.com/en-us/library/bb762914(v=vs.110).aspx
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)
}
}