File is not copying properly to the new location - c#

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.
}

Related

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

How Can I copy an exe file from My Visual Studio Project to My Desktop using C#? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have a problem about copying an exe file in my visual studio project folder to my computer desktop or somewhere else in my computer by using C#.
How can I do that?
This answer is directly from Microsoft website, please check the reference link.
The following example shows how to copy files and directories.
// 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();
}
}
Reference: Microsoft (06-02-2018).
Get your working directory:
string appDir = AppDomain.CurrentDomain.BaseDirectory;
Specify your target directory:
string targetDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
Get the file(s) you want using Directory.GetFiles:
FileInfo[] files = new DirectoryInfo(appDir).GetFiles(*.*, SearchOption.TopDirectoryOnly);
Copy your files:
try
{
foreach(FileInfo file in files)
{
File.Copy(file.FullName, Path.Combine(targetDir, file.Name), true);
}
}
catch (Exception ex)
{
//Handle DirectoryAccess errors and others
}

How to move subfolder with files to another directory in asp.net C#

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

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

How do I prevent this System.IO.IOException when copying a file?

When I run the following code to test copying a directory, I get a System.IO.IOException when fileInfo.CopyTo method is being called. The error message is: "The process cannot access the file 'C:\CopyDirectoryTest1\temp.txt' because it is being used by another process."
It seems like there's a lock on file1 ("C:\CopyDirectoryTest1\temp.txt") which is created a few lines above where the error is occurring, but I don't know how to release this if so. Any ideas?
using System;
using System.IO;
namespace TempConsoleApp
{
class Program
{
static void Main(string[] args)
{
string folder1 = #"C:\CopyDirectoryTest1";
string folder2 = #"C:\CopyDirectoryTest2";
string file1 = Path.Combine(folder1, "temp.txt");
if (Directory.Exists(folder1))
Directory.Delete(folder1, true);
if (Directory.Exists(folder2))
Directory.Delete(folder2, true);
Directory.CreateDirectory(folder1);
Directory.CreateDirectory(folder2);
File.Create(file1);
DirectoryInfo folder1Info = new DirectoryInfo(folder1);
DirectoryInfo folder2Info = new DirectoryInfo(folder2);
foreach (FileInfo fileInfo in folder1Info.GetFiles())
{
string fileName = fileInfo.Name;
string targetFilePath = Path.Combine(folder2Info.FullName, fileName);
fileInfo.CopyTo(targetFilePath, true);
}
}
}
}
File.Create returns an open FileStream - you need to close that stream.
Just
using (File.Create(file1)) {}
should do the trick.

Categories