to copy folders from local machine to folder in server - c#

to copy folders from local machto copy the complete files and folders , from local machine , i.e,
folder/directory path which is selected by user has to be completely[all
files within the path is be selected] is to be pasted/copied into
folder which is in webserver where the web application has been hosted.
ine to folder in server

Well, I've had quite a difficult time understanding your English. As I understood, your task is to make an exact copy of one folder including all nested folders and files, in some location?
If yes, then I would highly recommend using the console command xcopy for that, as it is perfomance-wise optimized and gives the benefit of copying the file-structure with all the related security permissions etc.

Try this:
string[] SourceFilez = System.IO.Directory.GetFiles("path", "*.*", System.IO.SearchOption.AllDirectories);
string[] targetFilez = new string[SourceFilez.Length];
SourceFilez.CopyTo( targetFilez, 0 );
for(int i = 0; i < targetFilez.Length; ++i)
{
targetFilez[i] = targetFilez[i].Replace("oldfolder", "newfolder");
string strThisDirectory = System.IO.Path.GetDirectoryName(targetFilez[i]);
if (!System.IO.Directory.Exists(strThisDirectory))
{
System.IO.Directory.CreateDirectory(strThisDirectory);
}
System.IO.File.Copy(SourceFilez[i], targetFilez[i]);
}
You might want to include the for loop content in a try-catch-finally block.
To account for empty directories, you might want to repeat the same code-block without file.copy, replacing SourceFilez with:
string[] SourceDirectories = System.IO.Directory.GetDirectories("path", "*.*", System.IO.SearchOption.AllDirectories);
If you have IIS7 and the user does not have the necessary permissions to write to the target folder, you need to use identity impersonate and switch the app-pool to classic mode.
Edit:
Or do you mean a way to upload all files in a folder on a web-application's user's computer to the server at once ? In that case you need JQuery uploadify:
http://www.uploadify.com/

Related

Why do I get message "Access to the path 'bootmgr' is denied " when trying to clear the contents of a directory

Using Windows 10 Home (20H2) on HP Spectre
I am trying to use the following code to clear the contents of a directory
public int clearDirectory(string path)
{
DirectoryInfo targetDir = new DirectoryInfo(path);
foreach (FileInfo file in targetDir.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in targetDir.GetDirectories())
{
dir.Delete(true);
}
return 0;
}
The target directory is on a USB SanDisk which has in its root dir one directory (which has a number of subdirectories) which I created and the following SanDisk files
SanDiskMemoryZone_AppInstaller.apk
SanDiskMemoryZone_QuickStartGuide.pdf
I replaced the path to the USB drive with a path to a directory on my C drive and that worked fine.
How does the bootmgr get involved in this?
In Windows you can declare for each drive if it is bootable or not.
The bootable partition in Windows is a hidden drive called system partition (and that‘s also the reason why no error was shown when you tried to delete the C:-drive)
Your SAN-drive seems to be using a file system which has a hidden folder with ACL only for the system account.
That‘s why you get this error. You have no access right to delete the file/folder.
One solution:
change your code s.t. It only selects files without a leading dot, like with regex: ^\.
If this still doesn’t fix your error then you should try use an elevated process (with adminr rights) to tackle this.
REMARK: before you delete everything from a usb stick, it would be easier to just reformat it then deleting every file.
Maybe look into Diskpart for this.

How to always write to an existing local drive using C# StreamWriter

Apologies for the poor title wording,
I have a StreamWriter set up in my C# program that creates and then writes to multiple text files on a local storage drive. The issue is that as I test this program on multiple machines - the names of the drives are inconsistent from machine to machine and do not always have a C: , D: , etc. As a result I experience errors whilst trying to write to drives that do not exist.
I have attempted to not specify the drive to be written to in the hopes that it would default to an existing drive as the specific location is unimportant for my needs. I.e. "C:\\wLocation.txt" becomes "wLocation.txt" but this did not seem to fix anything.
Code:
public static string getWeatherLocation()
{
String locationFile = "C:\\wLocation.txt";
String location;
try
{
System.IO.StreamReader reader = new StreamReader(locationFile);
location = reader.ReadLine();
reader.Close();
return location;
}
catch (Exception ex)
{
return null;
}
}
I'm not particularly knowledgeable with regards to the StreamWriter so the solution may be fairly simple but any help would be appreciated.
You can use System.IO.DriveInfo.GetDrives to get a list of drives on the machine:
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
Console.WriteLine(d.Name); //C:\ etc.
}
You can then simply compose the file name of the given volume label and your desired file name:
var filePath = d.Name + "filename.txt";
Or better:
var filePath = Path.Combine(d.Name, "filename.txt");
In order to cope with different drives on different machines, you have several options:
Use relative file paths, e.g. locationFile = "wLocation.txt" will write the file in the current directory.
Use a special folder, e.g. Documents or AppData. You can use the Environment.GetFolderPath method to get one of those directories and create the full path like this: locationFile = Path.Combine(sysFolderPath, "wLocation.txt");.
Make the folder configurable in your application.
Please note that besides getting a folder path that works on the specific machine, you also need to pay attention to the permissions of the directory. Especially the first option might not work due to permissions if you install your application under Program Files.

Trying to delete folders that are either empty, or only have hidden files within

I'm trying to clean up my lightroom folders and have found that sometimes there are hidden files left behind from moving the files from them around.
I did some searching and was able to build this Frankenstein function, but every time it tries to delete an empty folder I get an error saying that the folder is in use by another process....
Basically I am trying to recurs through all of the folders and delete the ones that are empty children, or ones that only have hidden files within. This process should repeat through all of the folders removing their children and eventually the parent if there are no files (or only hidden files) contained therein.
Any help or suggestions would be greatly appreciated!
Cheers!
private static void processDirectory(string startLocation)
{
//For every folder in this folder, recurse into that folder and take a peek...
foreach (var directory in Directory.GetDirectories(startLocation))
{
processDirectory(directory);
//Get a handle to the directory to get files and whatnot from....
DirectoryInfo di = new DirectoryInfo(directory);
FileInfo[] files = di.GetFiles();
//We want to ignore any hidden files in the directory
var filtered = files.Where(f => !f.Attributes.HasFlag(FileAttributes.Hidden));
//Make sure there are no other files or directories behind this one
if (filtered.Count() == 0 && Directory.GetDirectories(directory).Length == 0)
{
//Okay it's safe, delete it now.
di.Delete();
}
}
}
Well if this weren't bizarre enough, this morning when I ran the code it worked just fine!? My folders have been pruned down to only the ones that actually have photos in them, and life is good.
The one thing that I did have to do is add true to the di.Delete() function. This was because the function was stopping on folders that had hidden files in them.
I am assuming it was something along the lines of what Chris posted above and some latent function was still open from Adobe.
Thanks to everyone that posted a reply!
Cheers!

Get the size of readonly file with GetFiles()

Does anybody know why I am not allowed to "read" the size of a file that has the "ReadOnly" bit set? I am running my program as Administrator and I am not attempting to write to the file, I can read properties and file size from File Explorer just fine, even with lower credentials, but my software is not allowed to read from a readonly file and gives me an UnAuthorizedAccess exception. I don't see any logic behind this, anybody who does? Is there a workaround?
private static double DirSize(DirectoryInfo tdir) {
double size = 0;
FileInfo[] files = tdir.GetFiles();
foreach (FileInfo file in files) { size += file.Length; }
DirectoryInfo[] dirs = tdir.GetDirectories();
foreach (DirectoryInfo dir in dirs) { size += DirSize(dir); }
return( size );
}
Edit: the file it's complaining about is a shortcut to a directory that is readonly. Security tab shows no problems on both the directory itself and the shortcut. I guess it's not a big deal cause it's just a shortcut, but I like to understand what's going on and want to count that 1 KB shortcut to my totals.
On Windows, files and directories have different security credentials. You may access a file of a directory easily, but when it comes to a directory itself, you will need to set privileges for the user of your application.
Properties -> Security -> Groups or Usernames
And you must give access to the user of the application which is trying to access the data. (For example IIS user For web applications)

Why are permissions wonky when my IIS worker saves a file in ASP.NET?

IIS 8, ASP.NET MVC 4, .NET 4.5
private static string SaveProfilePicFile(UserProfileViewModel model)
{
var tempFilename = Path.GetTempFileName();
model.ProfilePic.Profile.UploadedFile.SaveAs(tempFilename);
var staticContentFilename = Helpers.GetStaticContentFilename(
StaticContentType.Avatar, model.ProfilePic.Profile.UserId);
var destinationFilename = Path.Combine(
ConfigurationManager.AppSettings["StaticContentPath"],
"profile",
staticContentFilename);
if (File.Exists(destinationFilename))
File.Delete(destinationFilename);
if (!HasJpegHeader(tempFilename)) // convert temp file into JPG
{
using (var image = new Bitmap(tempFilename))
image.Save(destinationFilename, ImageFormat.Jpeg);
File.Delete(tempFilename);
}
else
{
File.Move(tempFilename, destinationFilename);
}
return staticContentFilename;
}
I'm not interested in a code review, I know things could be done better. Right now I've hit an unusual problem. StaticContentPath points to c:\inetpub\wwwroot\static.domain.com, which is being served by a different application pool which is configured to disable scripting and cache things heavier. If I manually place a file in the static content folder, it will serve correctly. If the above code (from a different application pool) saves a file there, the permissions are very unusual. I'll attach screenshots.
The "default" file is one I pasted manually. It properly inherited permissions from the parent folder. The hashed filename was saved by the above code, and it does not inherit permissions properly. When I attempt to access the file, I get a very basic error message from IIS, the entirety of which is "The page cannot be displayed because an internal server error has occurred." No styling, nothing I'm used to seeing with IIS errors. If I manually add read permissions to the IIS_IUSRS account everything works as I'd expect.
Why is this happening, what can I do to mitigate it, and does my code need to be updated?
I suspect the problem is with the use of Path.GetTempFileName followed by File.Move. When the uploaded file is saved to tempFilename, the temporary file gets whatever permissions are assigned to the temporary folder. Moving the file preserves those permissions as is instead of recalculating the inheritable permissions based on the destination.
Instead of File.Move, try using File.Copy followed by File.Delete:
//File.Move(tempFilename, destinationFilename);
File.Copy(tempFilename, destinationFilename);
File.Delete(tempFilename);

Categories