Copy multiple files from one share folder to different folder share - c#

I have list of files which i need to copy to a different share folder with same folder structure.
Input:
\\myshare1\foldername1\foldername2\file1.txt
\\myshare1\foldername1\foldername2\file2.txt
\\myshare1\foldername3\foldername4\file1.txt
\\myshare1\foldername3\foldername1\file4.txt
Output : Copy all the files to \\myshare2 with the same folder structure. If the folder is there skip the folder creation and if not create the folder.
\\myshare2\foldername1\foldername2\file1.txt
\\myshare2\foldername1\foldername2\file2.txt
\\myshare2\foldername3\foldername4\file1.txt
\\myshare2\foldername3\foldername1\file4.txt

Just do a foreach on your folder to get all the file names and send each file to the following method
public void CopyFiles(string sourcePath)
{
string destination = "myshare2";
string source = sourcePath.Replace("myshare1","");
if (!System.IO.Directory.Exists($"{destination}{source}"))
{
System.IO.Directory.CreateDirectory($"{destination}{source}");
System.IO.File.Copy(sourcePath, $"{destination}{source}", true);
}
}

Related

How can i download just my pdf file an not the full file path and folders

So I finally got this to work and download my pdf files into a zip file. See below:
List<string> manypaths = (List<string>)TempData["temp"];
var startpath = manypaths;
using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
{
zip.AddFiles(manypaths);
MemoryStream output = new MemoryStream();
zip.Save(output);
return File(output.ToArray(), "application/zip");
}
So the manypaths list variable is holding onto a few paths to the pdf file which are like \\\\ost-stji01\pdfstorage\deposit\02_29_2019.pdf
So when the user downloads these files they have to click through multiple folder structure i.e ost0ji01 > pdfstorage > desposit > then they get to their file.
My question is how can i download just the files and not the entire folder structure. SO when they open the zip file its all of the files and they don't have to go through 3 or 4 folder directories.
If you want to flatten the paths in your ZIP file, use this.
zip.AddFiles(manypaths, #"\");
The second parameter of AddFiles allows you to specify the path of your files in the archive and \ is the root in your archive. Therefore, all files will be located directly in your archive without subfolders.

Delete all folders in parent folder except where sub folder contains specific file

I'm having problems keeping 1 folder which contains an image I want to keep.
I'm currently using the code below:
DirectoryInfo di = new DirectoryInfo(pathToMedia);
foreach (var image in di.GetFiles())
{
if (!image.Name.Contains(emailImage))
{
di.Delete(true);
}
}
The above does not work as I cannot seem to get the file name of the image inside the sub-folder, any help would be appreciated
The code is not able to find the file as GetFiles(string) method only returns the file in the current directory and not in the sub-folders (an overload exists which allows to get all files, but that wont be useful here as we need the directory information as well). If you want to check for the files in all sub-folders then you will have to recursively do through the entire structure.
The code below shows how to do it, in your case instead of writing to console you will just check if it matches to the file you are searching.
You can see the detail about these methods in api documentation
As mentioned in the documentation it might be beneficial for you to use EnumerateFiles in case your folders are going to have a large number of files.
// Process all files in the directory passed in, recurse on any directories
// that are found, and process the files they contain.
public static void ProcessDirectory(string targetDirectory)
{
// Process the list of files found in the directory.
string [] fileEntries = Directory.GetFiles(targetDirectory);
foreach(string fileName in fileEntries)
ProcessFile(fileName);
// Recurse into subdirectories of this directory.
string [] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach(string subdirectory in subdirectoryEntries)
ProcessDirectory(subdirectory);
}
// Insert logic for processing found files here.
public static void ProcessFile(string path)
{
Console.WriteLine("Processed file '{0}'.", path);
}

C# - Access to Path is Denied, unable to access files

I'm working on a project that a series of images that are deposited in one area of memory (say from a memory stick or download), and distributes them out to their respective folders based on the name of the image - which should correspond with the names of the files in their respective folder.
I have the first few functions of the code written to make this happen and decided to test it by altering the code so that it would carry out the process on a collection of the files in the My Pictures folder.
What should have happened is that each file in the folder was copied to a folder in AppData called 'New Images', and added into the appropriate sub-directory or create the subdirectory if necessary.
This threw up an error stating that access to C:\Users\mark although it did not explain why or what to do about it.
I thought this might be a problem with accessing the My Pictures folder so I copied the images into a folder called 'Test Images' inside the AppData folder (so the program would now be just transferring files between two folders in AppData). The same error occurred and I don't really know what to do next, I have written and read from files in AppData many times before and never encountered this problem. I have also read various entries related to this on this forum but don't seem to be able to get a definitive answer in terms of what to do next!
The code that causes the exception can be seen below:
//main folder (Contains sub-folders for each patient)
string rootDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\New Images";
//variables for sub-directories cannot be given at this point as they are created using a part of the image name
string subDirectory;
//string subDirectory = Path.Combine(rootDirectory, imageName.Split('_')[0]);
string imageName;
//string imageName = Path.GetFileName(image)
string shortcutDirectory;
//string shortcutDirectory = My Documents + Subfolder name + file name
//list to hold all strings as bitmap image
List<Bitmap> images = new List<Bitmap>();
public void createDirectory()
{
//create filing construct for all files passed in from machines
//if main folder does not exist in AppData
if (!Directory.Exists(rootDirectory))
{
//create it
Directory.CreateDirectory(rootDirectory);
}
}
public void saveLatestImages()
{
//specific path for My Pictures only
string testImagesPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Test Images";
//if there is a Pictures folder
if (Directory.Exists(testImagesPath))
{
//get number of files in folder
int fileCount = Directory.GetFiles(testImagesPath).Count();
//more than one file in folder
if (fileCount > 0)
{
//create data structures to store file info
//filePaths holds path of each file represented as a string
string[] filePaths = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Test Images");
//for each file in Pictures...
for (int index = 0; index < fileCount; ++index)
{
//get name of image at current index
imageName = filePaths[index];
//separate the part relating to the patient name (everything before (DD/MM/YYYY))
string subSpecifier = imageName.Split('_')[0];
//add to root directory to form subfolder name
subDirectory = Path.Combine(rootDirectory, subSpecifier);
//subdirectory name formulated, check for pre-existing
//subfolder does not exist
if(!Directory.Exists(subDirectory))
{
//create it
Directory.CreateDirectory(subDirectory); //ERROR OCCURS
}
//otherwise, file will be added to existing directory
//take everything from end and folder\file division to get unique filename
string fileName = imageName.Split('\\').Last();
//add this to the existing subDirectory
fileName = Path.Combine(subDirectory, fileName);
//copy the image into the subfolder using this unique filename
File.Copy(imageName, fileName);
//add full filename to list of bitmap images
images.Add(new Bitmap(fileName));
//update the shortcut to the file in the image storage shortcut folder
shortcutDirectory = getShortcut(subSpecifier, fileName);
//delete image at original path (clear folder so images not copied on next load up)
//File.Delete(imageName);
}
}
}
}
Any help in where to look next would be greatly appreciated!
Thanks
Mark
Is this an ASP.net web application ? In that case can you try providing write permission to the IIS_IUSRS account.
The trick to solve this is ASP.net Impersonation .
Do not give full rights and run your app as an admin. Users will then have admin rights and I am sure you would want to avoid that.
For time being give full rights to everyone to your folder and try running your application as an administrator.
If that works then your can change permissions on your folder accordingly. Also make sure that your folder isn't readonly.

How to skip to copy Read only Directories in C#

I trying to write a code that will copy all files from give directory and its all sub directories. (Only copy files not directories).
This is so far i have
public static void Copy(string sourceDir, string targetDir)
{
Directory.CreateDirectory(targetDir);
foreach(var file in Directory.GetFiles(sourceDir))
File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file)),true);
foreach(var directory in Directory.GetDirectories(sourceDir))
Copy(directory, Path.Combine(targetDir, Path.GetFileName(directory)));
}
I am facing two problems here.
I get unauthorized Access exception. There is a folder in source directory that is creating problem.
2nd problem is. If it copies it copy all files and folder as it is in the source directory. but I only need files.
Any solution for both problems ?
OK to copy all sub directories, and so on, omitting any that wont let you have access:
Before you call copy, you would need to check targetDir exists.
if (!Directory.Exists(targetDir)) Directory.CreateDirectory(targetDir);
you should really check it can do that etc, then to recursively copy the folders into the same one:
public static void Copy(string sourceDir, string targetDir)
{
try
{
foreach(var file in Directory.GetFiles(sourceDir))
try
{ File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file)),true);}
catch {} // you could do other things to handle different issues - like lack of space, etc
foreach(var directory in Directory.GetDirectories(sourceDir))
Copy(directory, targetDir)); // this will go into each subdirectory, and do the same.
}
catch {} // catches unable to access directory you've gone into
}
}
You keep the final destination the same if you wanted a flat dump into a folder, by trying to append the path etc to copy you were recreating the whole directory structure.

Upload files to a specific folder in dropbox

I was using this example to upload files to dropbox:
https://github.com/geersch/DropboxRESTApi/blob/master/src/part-5/README.md
Which is:
public FileSystemInfo UploadFile(string root, string path, string file)
{
//...
}
The method has 3 parameters:
root: The root relative to which the path is specified. Valid values
are sandbox and dropbox.
path: The path to the file you want to
upload.
file: Absolute path to the local file you want to upload
Call this method as follows:
var file = api.UploadFile("dropbox", "photo.jpg", #"C:\Pictures\photo.jpg");
Dropbox API says exactly the same as the example:
https://www.dropbox.com/developers/core/docs#files-POST
So no mentioning of "parent folder"..
How can I upload files under a specific folder instead of the root?
cant you just do
var file = api.UploadFile("dropbox", #"myfolder\photo.jpg", #"C:\Pictures\photo.jpg");
I have the same issue.
I use this method for combining paths as the target directory
public static string CombinePath(string folder, string filename) => folder == "/" ? $"/{filename}" : $"{folder}/{filename}";
If you need to upload your file into the root directory the only parameter is / to identify the root.

Categories

Resources