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());
}
}
Related
I have written a c# code to copy a csv file to a new location.
If the file already exists in the target location file should be deleted and paste the new file back.
This process should be recurring and runs in the background since the csv file is updating every 5 minutes.
The current issue is even the file was deleted in the target path the new file won't be written back.
My code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace filemove
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
}
public void Start()
{
mysql();
}
static void mysql()
{
string fileName = "data.csv";
string sourcePath = #"\\192.168.16.12\Users";
string targetPath = #"C:\Users\Admin\source";
// 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);
FileInfo info = new FileInfo(destFile);
bool exists = info.Exists;
if (exists == true)
{
File.Delete(#"C:\Users\Admin\source\Bargstedt.csv");
}
else
{
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();
}
public void OnStop()
{
}
}
}
Can anyone figure out what's the error is?
File.Delete actually doesn't throw any exception if file doesn't exists. So, I will just remove a check for exists entirely.
try {
int delay = 400;
File.Delete(#"C:\Users\Admin\source\Bargstedt.csv");
Thread.Sleep(delay); // to prevent delete and copy happening at the
// same time.
System.IO.File.Copy(s, destFile, true);
}catch (IOException ex) {}
You can also check at this post:
FileStream and a FileSystemWatcher in C#, Weird Issue "process cannot access the file"
and user EventHorizon's answer checking for if file is closed.
Its also advisable to check whether directory has permissions (FileIOPermissionAccess.Write)
I think you mean to write the file even if there was a file.
You're using:
bool exists = info.Exists;
if (exists == true)
{
File.Delete(#"C:\Users\Admin\source\Bargstedt.csv");
}
else
{
System.IO.File.Copy(s, destFile, true);
}
Remove the else:
bool exists = info.Exists;
if (exists == true)
{
File.Delete(#"C:\Users\Admin\source\Bargstedt.csv");
}
System.IO.File.Copy(s, destFile, true);
Use this to copy a file when it is existing in target path and with a backup plan for that existing file.
// To copy a file to another location and
// overwrite the destination file if it already exists.
if (!File.Exists(destFile))
{
System.IO.File.Copy(sourceFile, destFile, true);
}
else
{
System.IO.File.Move(destFile, existingFilePath); //if file is existing and then move it to specific folder
try
{
System.IO.File.Copy(sourceFile, destFile, true);
}
catch (Exception)
{
System.IO.File.Move(existingFilePath, destFile); //If anythig went wrong, old file is relocated correctly
}
System.IO.File.Delete(existingFilePath); // Delete old file, all is ok now.
}
I want to copy and paste sub-folders of source folder ABC To destination folder. But it is not working. Here is my C# code, it work's fine but it copies the whole folder instead of only the sub-folders.
// string fileName = "test.txt";
string sourcePath = "D:\\Shraddha\\Demo_Web_App\\Source";
string targetPath = "D:\\Shraddha\\Demo_Web_App\\Destination";
// Use Path class to manipulate file and directory paths.
string sourceFile = System.IO.Path.Combine(sourcePath);
string destFile = System.IO.Path.Combine(targetPath);
// 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);
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();
Alright, here we go:
This doesn't really makes sense. If targetPath exists, create targetPath folder?
if (System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
You probably meant:
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
What you need to do first is, getting all directories to begin with:
var allDirectories = Directory.GetDirectories(targetPath, "*", SearchOption.AllDirectories);
then you can loop through allDirectories with foreach, find all files in each folder and copy the contents.
The following line cannot work like provided:
destFile = System.IO.Path.Combine(targetPath);
File.Copy expects a path to a file where you want to copy the content from "s", but you are providing only the destination folder. You have to include a filename in the Path.Combine method.
If you parse the path strings with the Path.GetFileName method for example, you can pass the result (only the filename without full source path) as an additional argument to Path.Combine to generate a valid destination path.
Additionally, like uteist already said, you have to get all subdirectories first, because in your code example, you're only copying the files, directly placed under your root source folder.
To keep the Directory structure
foreach (var dir in System.IO.Directory.GetDirectories(sourcePath))
{
var dirInfo = new System.IO.DirectoryInfo(dir);
System.IO.Directory.CreateDirectory(System.IO.Path.Combine(targetPath, dirInfo.Name));
foreach (var file in System.IO.Directory.GetFiles(dir))
{
var fileInfo = new System.IO.FileInfo(file);
fileInfo.CopyTo(System.IO.Path.Combine(targetPath, dirInfo.Name, fileInfo.Name));
}
};
I'm learning how to create text file in C# but I have a problem. I used this code:
private void btnCreate_Click(object sender, EventArgs e)
{
string path = #"C:\CSharpTestFolder\Test.txt";
if (!File.Exists(path))
{
File.Create(path);
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("The first line!");
}
}
else if (File.Exists(path))
MessageBox.Show("File with this path already exists.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
When I press the "Create" button, Visual Studio shows an error 'System.IO.DirectoryNotFoundException', which points at "File.Create(path)".
Where is the problem?
Well supposing that your directory exists (as you have said) then you have another problem
File.Create keeps locked the file that it creates, you cannot use the StreamWriter in that way.
Instead you need to write
using(FileStream strm = File.Create(path))
using(StreamWriter sw = new StreamWriter(strm))
sw.WriteLine("The first line!");
however all this is not really necessary unless you need to create the file with particular options (see File.Create overload list) because StreamWriter creates the file itself if it doesn't exist.
// File.Create(path);
using(StreamWriter sw = new StreamWriter(path))
sw.WriteLine("Text");
...or all on one line
File.WriteAllText(path, "The first line");
The exception is indicating that your Directory C:\CSharpTestFolder doesn't exist. File.Create will create a file in existing folder/path, it will not create the full path as well.
Your check File.Exists(path) will return false, since the directory doesn't exists and so as the file. You need to check Directory.Exists on the folder first and then create your directory and then file.
Enclose your file operations in try/catch. You can't be 100% sure of File.Exists and Directory.Exists, there could be other process creating/removing the items and you could run into problems if you solely rely on these checks.
You can create Directory like:
string directoryName = Path.GetDirectoryName(path);
Directory.CreateDirectory(directoryName);
(You can call Directory.CreateDirectory without calling Directory.Exists, if the folder already exists it doesn't throw exception) and then check/create your file
You have to create the directory first.
string directory = #"C:\CSharpTestFolder";
if(!Directory.Exists(directory))
Directory.CreateDirectory(directory);
string path = Path.Combine(directory, "Test.txt");
if (!File.Exists(path))
{
File.Create(path);
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("The first line!");
}
}
else if (File.Exists(path))
MessageBox.Show("File with this path already exists.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
Try this.
string path = #"C:\CSharpTestFolder";
if (Directory.Exists(path))
{
File.AppendAllText(path + "\\Test.txt", "The first line");
}
else
{
Directory.CreateDirectory(path);
File.AppendAllText(path + "\\Test.txt", "The first line");
}
The File.AppendAllText(path, text) method will create a text file if it does not exist; append the text and will close the file.
If the file already exists, it will open the file and append the text to it and then close the file.
The exception shows that the directory C:\CSharpTestFolder does not exist.
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)
}
}
Why would the code below throw a io.system.directorynotfound exception? I can't recreate the problem myself but another user of my code does see it, any ideas why?
Thanks
try
{
//create path
string strAppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString() + "\\MyApp\\Data\\logs";
//check path exists
if (!System.IO.File.Exists(strAppData))
{
System.IO.Directory.CreateDirectory(strAppData);
}
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(strAppData);
int count = dir.GetFiles().Length;
if (count > 100)
{
string[] files = System.IO.Directory.GetFiles(strAppData);
foreach (string file in files)
{
System.IO.File.Delete(file);
}
}
this.fileName = fileName;
// delete the file if it exists
if (File.Exists(fileName))
{
//delete the file
File.Delete(fileName);
}
// write the data to the file
fs = File.OpenWrite(fileName);
sWriter = new StreamWriter(fs);
sWriter.WriteLine(headerText);
sWriter.Flush();
sWriter.Close();
}
catch (Exception exp)
{
throw new Exception(exp.Message);
}
Have you tried using System.IO.Directory.Exists rather than System.IO.File.Exists when checking to see if the path exists?
You're checking for the existence of a directory using System.IO.File rather than System.IO.Directory. It probably works on your machine because that directory already exists, and so the check doesn't matter.
Either way, you need to remember that the file system is volatile. Rather than checking existence, try to open the resource and handle the exception when it fails.
Check that the directory exists, not the file...
Although you're checking it, and creating it if it doesn't exist. You don't know if they have privelages to create the directory. So your Directory.CreateDirectory call may well be failing too and then sub-sequently the rest of the code will fail
http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx
"Remarks
The Exists method should not be used for path validation, this method merely checks if the file specified in path exists. Passing an invalid path to Existsl returns false. "
That is your error right there. Your validation does not ensure that the path to the file exists