Cannot create a file when it already exists using File.Move - c#

I was trying to move a file from my Resx to my PC, but I'm keep having problems.
So I import a folder named "bad" in the Resources and I use the File.Move method to move the folder "bad" into my PC.
But the program keeps crashing because it says: Cannot create a file when its already exists.
Here the code I use:
//txtpath is the root folder. I let the user choose the root folder and save it in txtpath.text
private void btnbadname_Click(object sender, EventArgs e)
{
string source = "Resources\bad";
string destination = txtpath.Text + #"\RADS\projects\lol_air_client\releases\0.0.1.74\deploy\assets\locale\App";
File.Move(source, destination);
MessageBox.Show("脏话ID已开启, 教程请点击下面的链接");
}

The destination Directory cannot exist. In your code you are creating the Directory if it doesn't exist and then trying to move your directory, the Move Method will create the directory for you. If the Directory already exists you will need to Delete it or Move it.
See:
Cannot create a file when that file already exists when using Directory.Move

Destination supposed to have the filename as well
string destination = txtpath.Text + #"\RADS\projects\lol_air_client\releases\0.0.1.74\deploy\assets\locale\App\yourfilename.ext";

You are using File.Move to move directory, why not using Directory.Move.
The MSDN documentation will only move files from a source to a destination, while Directory.Move will move the directory itself.
If I misunderstood you, and you want to move a file;
You can check if the file exists before or not using something like:
if(File.Exists(fileName))
File.Delete(fileName);
Edit:
If you want to iterate through the directory and make sure that the file doesn't exist before moving it, you can use something like:
//Set the location of your directories
string sourceDirectory = #"";
string destDirectory = #"";
//Check if the directory exists, and if not create it
if (!Directory.Exists(destDirectory))
Directory.CreateDirectory(destDirectory);
DirectoryInfo sourceDirInfo = new DirectoryInfo(sourceDirectory);
//Iterate through directory and check the existance of each file
foreach (FileInfo sourceFileInfo in sourceDirInfo.GetFiles())
{
string fileName = sourceFileInfo.Name;
string destFile = Path.Combine(destDirectory, fileName);
if (File.Exists(destFile))
File.Delete(destFile);
//Finally move the file
File.Move(sourceFileInfo.FullName, destFile);
}

When using MoveTo, provide the full path of where you are sending the file, including the file name, eg, pic123.jpg. If you use DirectoryInfo to get an array of files and want to move any of them, append the Name property of the file to the directory path where you are sending the file.
imgFile.MoveTo("C:\myPictures\ArchiveFolder\pic123.jpg")

Related

Move Directory Into Current Directory C#

I want to do something simple. Take the contents of folder A and move the files and folders into a folder within folder A. Then make folder A hidden.
The code below is getting an exception of hiddenTarget is not found.
Directory.Create(hiddenTarget) is not helping
There must be a simple way to do this. Currently I am attempting to make a temp directory. Put all files from the current directory in it. Then Move the temp directory to the current directory. Then make the current directory hidden.
Here is the code in issue..
string tempFolder = Path.Combine(Environment.ExpandEnvironmentVariables("%TEMP%"), "tempTarget");
//Directory.CreateDirectory(tempFolder);
Directory.Move(currentTarget, tempFolder);
string hiddenTarget = Path.Combine(currentTarget, #".bak");
//Directory.CreateDirectory(hiddenTarget);
Directory.Move(tempFolder, hiddenTarget);
DirectoryInfo di = new DirectoryInfo(currentTarget);
di.Attributes = FileAttributes.Directory | FileAttributes.Hidden;
So you have two issues here first is that your hidden target cannot start with a '.' because as pointed out in the comments that is illegal in NTFS.
As you can see File Explorer doesn't like this syntax.
As pointed out by #Dour High Arch here is the link to the relevant information: Naming Files, Paths, and Namespaces
Your next issue is that the move is destroying the original directory structure. Therefore, your steps need to be as follows:
1) Move to a temporary directory to avoid any issues with the two processes (file system & your process) fighting for access.
2) Due to the fact that the Directory.Move in step #1 destroyed the original source directory. Recreate the destroyed source folder.
3) Then move into the desired nested folder. This move operation will automatically create the desired sub-directory. Step #2 is required because for whatever reason I'm still looking into Directory.Move cannot automatically create the structure without the source directory already existing.
string currentTarget = #"C:\A";
string hiddenTarget = #"C:\A\Subfolder";
string tempTarget = #"C:\Temp";
Directory.Move(currentTarget, tempTarget);
Directory.CreateDirectory(currentTarget);
Directory.Move(tempTarget, hiddenTarget);
DirectoryInfo di = new DirectoryInfo(currentTarget);
di.Attributes = FileAttributes.Directory | FileAttributes.Hidden;
Update
From an engineering perspective you really should be performing copies if you really care about the data being moved. It may be slower, but will help prevent any horrible things from happening to the data. You should check whether or not these directories exist first before creating them. Exception handling within this example is at a minimum as well. What I'm really trying to stress here is handle the data that is being moved with care!
static void Main(string[] args)
{
string sourceDir = #"C:\Src";
string tempDir = #"C:\Temp";
string destDir = Path.Combine(sourceDir, "Dest");
// Could optionally check to verify that the temp directory already exists here and destroy it if it does.
// Alternatively, pick a really unique name for the temp directory by using a GUID, Thread Id or something of that nature.
// That way you can be sure it does not already exist.
// Copy to temp, then destroy source files.
CopyDirectory(sourceDir, tempDir);
Directory.Delete(sourceDir, true);
// Copy to dest
CopyDirectory(tempDir, destDir);
// Hide the source directory.
DirectoryInfo di = new DirectoryInfo(sourceDir);
di.Attributes = FileAttributes.Directory | FileAttributes.Hidden;
// Clean up the temp directory that way copies of the files aren't sitting around.
// NOTE: Be sure to do this last as if something goes wrong with the move the temp directory will still exist.
Directory.Delete(tempDir, true);
}
/// <summary>
/// Recursively copies all subdirectories.
/// </summary>
/// <param name="sourceDir">The source directory from which to copy.</param>
/// <param name="destDir">The destination directory to copy content to.</param>
static void CopyDirectory(string sourceDir, string destDir)
{
var sourceDirInfo = new DirectoryInfo(sourceDir);
if (!sourceDirInfo.Exists)
{
throw new DirectoryNotFoundException($"Source directory does not exist or could not be found: '{sourceDir}'");
}
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDir))
{
Directory.CreateDirectory(destDir);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = sourceDirInfo.GetFiles();
foreach (FileInfo file in files)
{
string tempPath = Path.Combine(destDir, file.Name);
file.CopyTo(tempPath, false);
}
// Copy subdirectories
DirectoryInfo[] subDirs = sourceDirInfo.GetDirectories();
foreach (DirectoryInfo subdir in subDirs)
{
string tempPath = Path.Combine(destDir, subdir.Name);
CopyDirectory(subdir.FullName, tempPath);
}
}
Here are a few more links regarding the above.
MSDN - How to: Copy Directories
Stack Overflow - How to copy the entire contents of directory in C#?

Directory.EnumerateFiles not retrieving the actual path

Am trying to loop through a folder and read all the XML files within it.
Am using the Directory.EnumerateFiles to read from the path.
My .cs file and the XML files folder lies in same path
"C:\User\Documents\Projects\TestTool"
Am using the below code to get read the files.
string path = #"..\TestCases\";
foreach(string file in Directory.EnumerateFiles(path, "*.xml"))
{
}
Using this am getting exception stating
Could not find path "C:\Program Files(x86)\Common Files\Microsoft
Shared\DevServer\TestCases"
This is pointing to the WebDev.WebServer20 path instead of the actual path.
Not sure why it is pointing to a completely different folder
I tried string path = #"\TestCases\"; But when I try like this it is throwing an exceptiopn stating
Could not find path "C:\TestCases"
What is the mistake am making? Please help
Try it:
string path = "..\\TestCases\\";
foreach (FileInfo file in new DirectoryInfo(path).EnumerateFiles("*.xml"))
{
string filePath = file.FullName;
}
Since it is running under WebDev server it will using WebDev.WebServer20.exe's path for all relative paths.
You must use: Server.MapPath("~") to get to your own root.
string path = Server.MapPath("~") + #"\TestCases\";
foreach(string file in Directory.EnumerateFiles(path, "*.xml"))
{
}
Please note if Server.MapPath("~") points to bin, then use it like Directory.GetParent(Server.MapPath("~")) + #"\TestCases\";
Assuming this is your target directory C:\User\Documents\Projects\TestTool\TestCases

moving file from one location to another without knowing file name

One of my executable process produces two files. I want to move one file that is produced to shared drive. I am writing an automatic process to move the file from one location to shared drive. The only issue is file name changes every time the executable is run so I don't have the exact filename with me. I only have the extension, .xls. I have only one .xls file in my directory.
I tried doing this
File.Copy(#"*.xls", #"\\serv44\Application\testing\name\test2\*.xls", true);
It threw an error saying Invalid name. After moving the file to shared drive. I want to delete the .xls file.
File.Delete("*.xls");
any help will be appreciated
You should get file name and then do whatever you want with that file. I.e. if you have only one xls file in the source directory:
var targetDirectory = #"\\serv44\Application\testing\name\test2\";
var sourceFile = Directory.EnumerateFiles(sourceDirectory, "*.xls").FirstOrDefault();
if (sourceFile != null)
{
var sourceFileName = Path.GetFileName(sourceFile);
var targetFileName = Path.Combine(targetDirectory, sourceFileName);
File.Copy(sourceFileName, targetFileName);
File.Delete(sourceFileName);
}
Note: instead of copy and delete you can use single Move operation.
If you want to move several files from your source directory, then instead of taking first one process all found files in a loop:
foreach(var sourceFile in Directory.EnumerateFiles(sourceDirectory, "*.xls"))
{
var sourceFileName = Path.GetFileName(sourceFile);
var targetFileName = Path.Combine(targetDirectory, sourceFileName);
File.Move(sourceFileName, targetFileName);
}
This should give you that file name:
var fileName = Directory.GetFiles(yourDirectory, "*.xls").ToList().FirstOrDefault();

How to copy a directory from local drive to a shared network using asp.net C#

Hello I am attempting to copy a directory and its subdirectories from my D drive to a shared network but I continue getting the error as
Exception:
Could not find a part of the path '/Projects/08.ASP.NETProjects/ProjectName/'.
My C# copy code:
System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(D drive path);
var destinationpath = "file:///BZ0025BZV43/Projects/08.ASP.NETProjects/ProjectName/";
var uri = new Uri(destinationpath);
var destinationurl = uri.AbsolutePath;
foreach (System.IO.FileInfo mydirectory in directory.GetFiles())
mydirectory .CopyTo(destinationurl);
I am new to FileHandlers. Please help.
Try to use uri.LocalPath instead of uri.AbsolutePath.
Also, be aware that you are trying to copy a file into a directory. But you have to copy the file into another file of that directory. (Directories are files too, basically).
So to do that check if the target directory exists and create it when necessary. Then replace .copyTo(destinationUrl) with .copyTo(Path.Combine(uri.LocalPath, mydirectory.Name)) and you should be good to go. And please rename the variable mydirectory to file or something similar.
Also note that you are not copying the directory tree recursively. So if you want to recurse the tree, you have to check for subdirectories and copy the files in that hierarchy, too.
You can also check out this example: http://msdn.microsoft.com/de-de/library/bb762914(v=vs.110).aspx

asp file upload control, which one should be use?

ok, i found this on internet to upload some files.
if (FileUpload1.HasFile)
{
//create the path to save the file to
string fileName = Path.Combine(#"E:\Project\Folders", FileUpload1.FileName);
//save the file to our local path
FileUpload1.SaveAs(fileName);
}
and this
//check to make sure a file is selected
if (FileUpload1.HasFile)
{
//create the path to save the file to
string fileName = Path.Combine(Server.MapPath("~/Files"), FileUpload1.FileName);
//save the file to our local path
FileUpload1.SaveAs(fileName);
}
what is the difference, which one to use? i got confuse. by the way, if i can store file path in database, and next time when i want to delete or see that file, how can i retrieve that? so let say, first i add a record to database and uploaded a .doc file / excel file, next time when i want to edit that record, i want to retrieve the uploaded file, and show it in UI. thanks.
use second one cause it will convert relative or virtual path to real path itself . .u should get path from db and use it to resolve the path the same way you are storing and do manipulation on it delete and etc. for displaying url="~/Files/yourfilename"
yourfilefromdb -u retrieve it from db
string filepath = Path.Combine(Server.MapPath("~/Files"), yourfilefromdb);
File.Delete(filepath);
for showing
if it accessible directly u can just write url="~/Files/yourfilefromdb"
The only difference in two code blocks posted you is in specifying file path.
In case 1, static location is specified to save the file. It can cause problem, if location to save files differ in your production environment. It will require rebuild in that case.
While, in case 2, location is specified using relative path. So, it will always save files at "/Files" location.
//if you already know your folder is: E:\ABC\A then you do not need to use Server.MapPath, this last one is needed if you only have a relative virtual path like ~/ABC/A and you want to know the real path in the disk...
if (FileUpload1.HasFile)
{
string fileName = Path.Combine(#"E:\Project\Folders", FileUpload1.FileName);// they know the right path so .they using directly
FileUpload1.SaveAs(fileName);
}
if (FileUpload1.HasFile)
{
string fileName = Path.Combine(Server.MapPath("~/Files"), FileUpload1.FileName);// i don't know path is correct or not so they using Server.MapPath. . .
FileUpload1.SaveAs(fileName);
}

Categories

Resources