Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Thursday, February 23, 2012 3:19 PM
Hey guys.
Is there any way I can upload one entire folder with FileUpload in C#
When I'm trying to upload, it only allows me to upload files, not folders. Is there any way I can do this?
All replies (2)
Thursday, February 23, 2012 4:05 PM ✅Answered
Simply create a folder on the target drive (if needed) and upload all the files in a folder to it... You could always wrap the process in a method called DirectoryUpload. Alternatively, if you want to do a proper job, you would use a recursive method similar to this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace CopyDirectoryTree
{
class Program
{
static void Main(string[] args)
{
CopyDirectoryStructure(@"C:\Documents and Settings\James\Desktop\TestFrom",
@"C:\Documents and Settings\James\Desktop\TestTo", true);
}
private static void CopyDirectoryStructure(string SourcePath, string DestinationPath, bool overwriteexisting)
{
try
{
SourcePath = SourcePath.EndsWith(@"\") ? SourcePath : SourcePath + @"\";
DestinationPath =
DestinationPath.EndsWith(@"\") ? DestinationPath : DestinationPath + @"\";
if (Directory.Exists(SourcePath))
{
if (Directory.Exists(DestinationPath) == false)
Directory.CreateDirectory(DestinationPath);
foreach (string fls in Directory.GetFiles(SourcePath))
{
FileInfo flinfo = new FileInfo(fls);
flinfo.CopyTo(DestinationPath + flinfo.Name, overwriteexisting);
}
foreach (string drs in Directory.GetDirectories(SourcePath))
{
DirectoryInfo diDi = new DirectoryInfo(drs);
CopyDirectoryStructure(drs, DestinationPath + diDi.Name, overwriteexisting);
}
}
}
catch (Exception ex)
{
}
}
}
}
Replace the lines where files are copied with your code to upload a file to the server and just change the names to thing that make sense to you. (And of course remove all the irrelevant lines - the code is just to illutrate using recursion to copy full directories and their subfolders). And add some proper exception handling. :)
James Finch (MCDST) -- Please vote as helpful if you found this post helpful, or mark as answer if it answered your question.
Thursday, February 23, 2012 4:16 PM ✅Answered
String path = Server.MapPath("~/Uploads/" + "somename"); //somename is the name of the folder
if (Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
DirectoryInfo di;
di = new DirectoryInfo("C:/KA/KG"); // source folder
foreach (FileInfo f in di.GetFiles())
{
f.CopyTo(path + "/" + f.Name); //files get copied in the Web Server path with the same folder and the files in it.
}
Simply create the folder with the same name as you want for your folder and then copy the files recursively.