I fetch a path from the Web.config file:
<appSettings>
<add key="Server" value="http://admin.xxxxxxx.com/1upload/*All File And Folder Copy this directory *"/>
<add key="Local" value="C:\\Users\\IND_COM\\Desktop\\xxxx\\1upload\\paste The Copyed File"/>
</appSettings>
In the button click event I pass the source and destination path:
protected void btnUpdate_Click(object sender, EventArgs e)
{
string Source_path = ConfigurationManager.AppSettings["server"].ToString();
string Detination_Path = "#" + ConfigurationManager.AppSettings["Local"].ToString();
DirectoryCopy(Source_path, Detination_Path, true);
}
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);//Exception Through In this Section..
if (!dir.Exists)
{
throw new DirectoryNotFoundException("Source directory does not exist or could not be found: "+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
On my hosting server, I have a folder and all images and XML saved in different folders. For example, I have 1 directory named 1Upload. Inside this directory I have 3 sub-directories and each has different files. I try to copy all 3 directories and files from the Server. This piece of code gives an exception
URI is not supported
HTTP is not a file system.
What you're looking to do is not to perform a file system copy operation, but rather to download the content from the web and save it to your file system. For this, you want something like the WebClient.DownloadFile() method.
For example:
var client = new WebClient();
client.DownloadFile(sourceURL, destinationFile);
Each file would be a separate request. You're currently trying to list directory contents of a website, which clearly won't work (because HTTP isn't a file system). However you build your list of files, once you have that list you can loop over it and call DownloadFile(source, destination) for each file.
If you need the website to provide a list of files, you have to add that functionality to the website (if it's not already there, we don't know). If you need to download all of the files in one operation, then the website would need to provide them in a single file (such as a .zip file).
Related
How to check which files have been downloaded in some particular folder in C#.net ? The files are kept by other application and not by the current .Net application.
region File Info
System.IO.DriveInfo di = new System.IO.DriveInfo(#"C:\Users\abc\Desktop\FileDownload");
Console.WriteLine(di.TotalFreeSpace);
Console.WriteLine(di.VolumeLabel);
// Get the root directory and print out some information about it.
System.IO.DirectoryInfo dirInfo = di.RootDirectory;
Console.WriteLine(dirInfo.Attributes.ToString());
// Get the files in the directory and print out some information about them.
System.IO.FileInfo[] fileNames = dirInfo.GetFiles("*.*");
foreach (System.IO.FileInfo fi in fileNames)
{
Console.WriteLine("{0}: {1}: {2}", fi.Name, fi.LastAccessTime, fi.Length);
}
// How to check if my files have been downloaded or still in progress of downloading.
Trying to copy all files/directories inside a directory to a new location that I create.
Users select the 'backup drive' to work with to in a combobox, then when they click the backup desktop button it simply creates a backup directory on that drive and copies all the files into that directory.
The backup directory gets created on the drive appropriately - but the first file it hits it kicks off an error.
private void backupDesktopButton_Click(object sender, EventArgs e)
{
//set the destionationLocation to the selectedDrive
string selectedDrive = backupDriveCombo.SelectedItem.ToString();
string destinationLocation = selectedDrive+"Backups-" + DateTime.Now.Month.ToString()+"-"+DateTime.Now.Year.ToString()+"\\Desktop\\";
if (!Directory.Exists(destinationLocation))
{
Directory.CreateDirectory(destinationLocation);
}
string desktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
string[] fileList = Directory.GetFiles(desktopFolder);
foreach (string file in fileList)
{
//move the file
File.Copy(file, destinationLocation);
}
}
I get the error:
IOException was unhandled.
The filename, directory name, or volume label syntax is incorrect.
In the 'Autos' window (VS2010) I see the locations are set correctly:
destinationLocation = the appropriate directory (C:\Backups-8-2016\Desktop\)
file = the appropriate first file (C:\Users\myusername\Desktop\myshortcut.url)
What am I missing? I have all rights to be able to copy/paste/create things and the directory to store it gets created - just a problem moving the file.
From the documentation https://msdn.microsoft.com/en-us/library/c6cfw35a(v=vs.110).aspx
the second parameter:
The name of the destination file. This cannot be a directory or an existing file.
you need to concat the filename to the folder.
Try something like this
string[] fileList = Directory.GetFiles(desktopFolder);
foreach (string file in fileList)
{
string targetFile = Path.Combine(destinationLocation, Path.GetFileName(file));
if (File.Exists(targetFile)) File.Delete(targetFile);
File.Copy(file, targetFile);
}
I am trying to use DirectoryInfo.MoveTo() to rename a directory that I have just extracted a Zip archive to. Most of the time the operation throws an IOException with the error Access to the path '...' is denied.. Occasionally, the operation works, but I haven't been able to correlate any condition that supports this. I've checked many forum posts and StackOverflow questions about this same error but I still cannot get this working. I'm sure its not computer permissions. All of these files and folders have full read/write permissions and I have tried running the program as an administrator.
Here is my code:
// Compute directory names
string directoryPathWithPrefix = Path.Combine(this.OutputDirectory.FullName,
"TEMP_ " + Path.GetFileNameWithoutExtension(compressedData.FullName));
string directoryPathWithoutPrefix = Path.Combine(this.OutputDirectory.FullName,
Path.GetFileNameWithoutExtension(compressedData.FullName));
// Extract file to new directory
ZipFile.ExtractToDirectory(compressedData.FullName, directoryPathWithPrefix);
// Add tag for UploadId
File.Create(Path.Combine(directoryPathWithPrefix,
upload.UploadId.ToString() + ".UPLOADID")).Close();
// Rename file
DirectoryInfo oldDir = new DirectoryInfo(directoryPathWithPrefix);
oldDir.MoveTo(directoryPathWithoutPrefix);
I've tried using Process Explorer to monitor the handle for the directory, but haven't been able to find any useful data from it. Using Directory.Move() or creating a ZipArchive object inside a using block still raise the error as well.
I'm really stumped on this one. Please help.
Clarification:
I'm running Windows 7 and this program is built under .NET 4.5
Here is the error I am receiving:
System.IO.IOException occurred
HResult=-2146232800
Message=Access to the path '{PATH}' is denied.
Source=mscorlib
StackTrace:
at System.IO.DirectoryInfo.MoveTo(String destDirName)
at DataImporter.ImportFDUU(FileSystemInfo uploadToImport, Message& reportMessage) in {CODE FILE}:line 380
InnerException:
Running cacls on the directory returns this information:
BUILTIN\Administrators:(OI)(CI)F
{MY USER}:(OI)(CI)F
I finally figured out the issue. Some strange glitch exists with ZipFile.ExtractToDirectory() that doesn't release access to a file in the directory when it is finished extracting. To get around this I changed my code as follows:
Extract the files to a temporary directory.
Copy the files from the temporary directory to the destination directory
Delete the temporary directory
// Compute directory names
string directoryPathWithPrefix = Path.Combine(this.SeparatorInputDirectory.FullName,
"TEMP_ " + Path.GetFileNameWithoutExtension(compressedFlightData.FullName));
string directoryPathWithoutPrefix = Path.Combine(this.SeparatorInputDirectory.FullName,
Path.GetFileNameWithoutExtension(compressedFlightData.FullName));
string tempDirectoryPath = Path.Combine(TempDirectoryPath, Path.GetDirectoryName(directoryPathWithoutPrefix));
// Extract file to new directory in the separator input directory
ZipFile.ExtractToDirectory(compressedFlightData.FullName, tempDirectoryPath);
// Add tag for UploadId
File.Create(Path.Combine(tempDirectoryPath,
upload.UploadId.ToString() + ".UPLOADID")).Close();
// Rename file to trigger separation
DirectoryCopy(tempDirectoryPath, directoryPathWithPrefix);
Directory.Move(directoryPathWithPrefix, directoryPathWithoutPrefix);
public static void DirectoryCopy(string sourceDirName, string destDirName)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
// 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)
{
string tempPath = Path.Combine(destDirName, file.Name);
file.CopyTo(tempPath, false);
}
// Copy subdirectories and their contents to new location.
foreach (DirectoryInfo subDir in dirs)
{
string tempPath = Path.Combine(destDirName, subDir.Name);
DirectoryCopy(subDir.FullName, tempPath);
}
}
I wanna do a C# application that does this:
Selects a folder
Copies all the files from that folder into that folder +/results/
Very simple, but can't get it work.
Here is my code:
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
foreach (string file in files)
{
MessageBox.Show(Path.GetFullPath(file));
//string path=Path.Combine(Path.GetFullPath(file), "results");
//MessageBox.Show(path);
string path2 = Path.GetDirectoryName(file);
path2 = Path.Combine(Path.GetDirectoryName(file), #"results\");
path2 = Path.Combine(path2, file);
MessageBox.Show(path2);
}
First, create the destination directory, if not exists
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
string destPath = Path.Combine(folderBrowserDialog1.SelectedPath, "results");
if(Directory.Exists(destPath) == false)
Directory.CreateDirectory(destPath);
then inside your loop
foreach (string file in files)
{
string path2 = Path.Combine(destPath, Path.GetFileName(file));
File.Move(file, path2);
}
Please note that File.Move cannot be used to overwrite an existing file.
You will get an IOException if the file exist in the destination directory.
If you only want to copy, instead of Move, simply change the File.Move statement with File.Copy(file, path2, true);. This overload will overwrite your files in the destination directory without questions.
If you are trying to move the files (and not copy them) to the new sub-folder then...
DirectoryInfo d = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
foreach (FileInfo f in d.GetFiles())
{
string fold = Path.Combine(f.DirectoryName, #"results\");
if (!Directory.Exists(fold))
Directory.CreateDirectory(fold);
File.Move(f.FullName, Path.Combine(fold, f.Name));
}
This is just an example to answer the question directly but you should also handle exceptions, etc. For instance, this example assumes the user will have permission to create the directory. Furthermore, it assumes file(s) do not already exist in the destination directory with the same name(s). How you handle such scenarios depends on your requirements.
If you want to relocate the entire directory, you can use Directory.Move to achieve this.
string path1 = Path.GetDirectoryName(file);
string path2 = Path.Combine(Path.GetDirectoryName(file), #"results\");
Directory.Move(path1, path2);
Or if you just want to copy the folder (without deleting the first directory), you'll need to do it manually.
string path1 = Path.GetDirectoryName(file);
string path2 = Path.Combine(Path.GetDirectoryName(file), #"results\");
foreach(var file in Directory.GetFiles(path1))
{
File.Copy(file, Path.Combine(path2, file));
// File.Move(file, Path.Combine(path2, file)); // use this to move instead of copy
}
I haven't tested this, so some modifications might be necessary
I need to Copy folder C:\FromFolder to C:\ToFolder
Below is code that will CUT my FromFolder and then will create my ToFolder.
So my FromFolder will be gone and all the items will be in the newly created folder called ToFolder
System.IO.Directory.Move(#"C:\FromFolder ", #"C:\ToFolder");
But i just want to Copy the files in FromFolder to ToFolder.
For some reason there is no System.IO.Directory.Copy???
How this is done using a batch file - Very easy
xcopy C:\FromFolder C:\ToFolder
Regards
Etienne
This link provides a nice example.
http://msdn.microsoft.com/en-us/library/cc148994.aspx
Here is a snippet
// 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);
}
}
there is a file copy.
Recreate folder and copy all the files from original directory to the new one
example
static void Main(string[] args)
{
DirectoryInfo sourceDir = new DirectoryInfo("c:\\a");
DirectoryInfo destinationDir = new DirectoryInfo("c:\\b");
CopyDirectory(sourceDir, destinationDir);
}
static void CopyDirectory(DirectoryInfo source, DirectoryInfo destination)
{
if (!destination.Exists)
{
destination.Create();
}
// Copy all files.
FileInfo[] files = source.GetFiles();
foreach (FileInfo file in files)
{
file.CopyTo(Path.Combine(destination.FullName,
file.Name));
}
// Process subdirectories.
DirectoryInfo[] dirs = source.GetDirectories();
foreach (DirectoryInfo dir in dirs)
{
// Get destination directory.
string destinationDir = Path.Combine(destination.FullName, dir.Name);
// Call CopyDirectory() recursively.
CopyDirectory(dir, new DirectoryInfo(destinationDir));
}
}
Copying directories (correctly) is actually a rather complex task especially if you take into account advanced filesystem techniques like junctions and hard links. Your best bet is to use an API that supports it. If you aren't afraid of a little P/Invoke, SHFileOperation in shell32 is your best bet. Another alternative would be to use the Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory method in the Microsoft.VisualBasic assembly (even if you aren't using VB).
yes you are right.
http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.aspx
has provided copy function ..
or you can use another function
http://msdn.microsoft.com/en-us/library/ms127960.aspx
You'll need to create a new directory from scratch then loop through all the files in the source directory and copy them over.
string[] files = Directory.GetFiles(GlobalVariables.mstrReadsWellinPath);
foreach(string s in files)
{
fileName=Path.GetFileName(s);
destFile = Path.Combine(DestinationPath, fileName);
File.Copy(s, destFile);
}
I leave creating the destination directory to you :-)
You're right. There is no Directory.Copy method. It would be a very powerful method, but also a dangerous one, for the unsuspecting developer. Copying a folder can potentionaly be a very time consuming operation, while moving one (on the same drive) is not.
I guess Microsoft thought it would make sence to copy file by file, so you can then show some kind of progress information. You could iterate trough the files in a directory by creating an instance of DirectoryInfo and then calling GetFiles(). To also include subdirectories you can also call GetDirectories() and enumerate trough these with a recursive method.
A simple function that copies the entire contents of the source folder to the destination folder and creates the destination folder if it doesn't exist
class Utils
{
internal static void copy_dir(string source, string dest)
{
if (String.IsNullOrEmpty(source) || String.IsNullOrEmpty(dest)) return;
Directory.CreateDirectory(dest);
foreach (string fn in Directory.GetFiles(source))
{
File.Copy(fn, Path.Combine(dest, Path.GetFileName(fn)), true);
}
foreach (string dir_fn in Directory.GetDirectories(source))
{
copy_dir(dir_fn, Path.Combine(dest, Path.GetFileName(dir_fn)));
}
}
}
This article provides an alogirthm to copy recursively some folder and all its content
From the article :
Sadly there is no built-in function in System.IO that will copy a folder and its contents. Following is a simple recursive algorithm that copies a folder, its sub-folders and files, creating the destination folder if needed. For simplicity, there is no error handling; an exception will throw if anything goes wrong, such as null or invalid paths or if the destination files already exist.
Good luck!
My version of DirectoryInfo.CopyTo using extension.
public static class DirectoryInfoEx {
public static void CopyTo(this DirectoryInfo source, DirectoryInfo target) {
if (source.FullName.ToLower() == target.FullName.ToLower())
return;
if (!target.Exists)
target.Create();
foreach (FileInfo f in source.GetFiles()) {
FileInfo newFile = new FileInfo(Path.Combine(target.FullName, f.Name));
f.CopyTo(newFile.FullName, true);
}
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories()) {
DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name);
diSourceSubDir.CopyTo(nextTargetSubDir);
}
}
}
And use like that...
DirectoryInfo d = new DirectoryInfo("C:\Docs");
d.CopyTo(new DirectoryInfo("C:\New"));