inefficient to efficient way to create subfolder in FTP - c#

I was using Make directory to create a folders and subfolder in my ftp (using filezilla) works fine,but when i try to do in my test server (IIS FTP) doesn't work ,throws 550,file not found or no access.so just a quick way to change the code to create subdirctory in my ftp server works fine but i know its a kinda shitty way to do like that.
Changed my code based on #Markus
var dir = new ConsoleApplication5.Program();
string path = "ftp://1.1.1.1/testsvr01/times/" + "testfile" + "/svr01fileName";
string[] pathsplit = path.ToString().Split('/');
string Firstpath = pathsplit[0] + "/" + pathsplit[1] + "/" + pathsplit[2] + "/" + pathsplit[3] + "/";
string SecondPath = Firstpath + "/" + pathsplit[4] + "/";
string ThirdPath = SecondPath + "/" + pathsplit[5] + "/";
string[] paths = { Firstpath, SecondPath, ThirdPath };
foreach (string pat in paths)
{
bool result= dir.EnsureDirectoryExists(pat);
if (result==true)
{
//do nothing
}
else
{ //create dir
dir.createdir(pat);
}
}
upload(path,filename);
}
private bool EnsureDirectoryExists(string pat)
{
try
{
//call the method the first path is exist ?
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(pat);
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential("sh", "se");
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
return true;
}
}
catch (Exception ex)
{ return false; }
}
public void createdir(string pat)
{
try
{
FtpWebRequest createdir = (FtpWebRequest)FtpWebRequest.Create(new Uri(pat));
createdir.Method = WebRequestMethods.Ftp.MakeDirectory;
createdir.Credentials = new NetworkCredential("sh", "se");
createdir.UsePassive = true;
createdir.UseBinary = true;
createdir.KeepAlive = false;
FtpWebResponse response1 = (FtpWebResponse)createdir.GetResponse();
Stream ftpStream1 = response1.GetResponseStream();
ftpStream1.Close();
response1.Close();
}
catch (Exception ex)
{
}
}
Please if any of you guys find a better way,suggest me.

That's a lot of code for ensuring a directory exists. Is there a Directory.Exists() method (or a similar method you could leverage)? Then you could call an EnsureDirectoryExists() before uploading.
private bool EnsureDirectoryExists(string path)
{
// check if it exists
if (Directory.Exists(path))
return true;
string parentPath = GetParentPath(path);
if (parentPath == null)
return false;
bool result = EnsureDirectoryExists(parentPath);
if (result)
{
CreateDirectory(path);
return true;
}
return false;
}
Disclaimer: You might need to tweak the logic a bit and use the FTP functions, but I hope you get the point.

Related

How to run a third party library method that potentially throws a StackoverflowException in a safe way c#

I'm using a third party library that converts excel files to PNG for preview purposes.
Sometimes the excel it's too complex, and the library fails with a StackoverflowException.
That's ok, because I don't except all files to be converted, but I can't catch the exception and give the user other option to download the file (Stackoverflow exceptions aren't catcheables)
I try to run in other thread using Task.Run() and even with a new request, but the original request stalls and I'm not able to control the fail.
Attempt 1 using Task.Run()
public string ExcelAsPNGUrl() {
try {
var TempFolder = #"/Content/Temp/";
var UniquePreviewFileName = ArchivoURL.Replace("/", "_") + ".png";
if (!System.IO.File.Exists( HttpContext.Current.Server.MapPath(TempFolder + UniquePreviewFileName))) {
var asyncTask = Task.Run(() => {
var UniquePreviewFileName = ArchivoURL.Replace("/", "_") + ".png";
var workbook = new Spire.Xls.Workbook();
workbook.LoadFromFile(HttpContext.Current.Server.MapPath(ArchivoURL));
var sheet = workbook.Worksheets[0];
sheet.SaveToImage(HttpContext.Current.Server.MapPath(TempFolder + UniquePreviewFileName));
return TempFolder + UniquePreviewFileName;
});
return asyncTask.Result;
}
return TempFolder + UniquePreviewFileName;
}
catch (Exception) {
return "";
}
}
Attempt 2 using WebClient
public string ExcelAsPNGUrl() {
try {
var TempFolder = #"/Content/Temp/";
var UniquePreviewFileName = ArchivoURL.Replace("/", "_") + ".png";
if (!System.IO.File.Exists( HttpContext.Current.Server.MapPath(TempFolder + UniquePreviewFileName))) {
var client = new System.Net.WebClient();
var retval = client.DownloadString(Sitio.URI + $"/system/GenerateExcelPreview?ArchivoURL={ArchivoURL}");
}
return TempFolder + UniquePreviewFileName;
}
catch (Exception) {
return "";
}
}
How can I call the library safely from my web app?

How to extract the .img files using c# [duplicate]

I'm trying to extract an ISO to a folder with the same name without .iso on the end.
I'm having a problem with winrar as it will not start the extract when I start up with the seach starting in the folder with the ISO.
UPDATED with answer code
private void ExtractISO(string toExtract, string folderName)
{
// reads the ISO
CDReader Reader = new CDReader(File.Open(toExtract, FileMode.Open), true);
// passes the root directory the folder name and the folder to extract
ExtractDirectory(Reader.Root, folderName /*+ Path.GetFileNameWithoutExtension(toExtract)*/ + "\\", "");
// clears reader and frees memory
Reader.Dispose();
}
private void ExtractDirectory(DiscDirectoryInfo Dinfo, string RootPath, string PathinISO)
{
if (!string.IsNullOrWhiteSpace(PathinISO))
{
PathinISO += "\\" + Dinfo.Name;
}
RootPath += "\\" + Dinfo.Name;
AppendDirectory(RootPath);
foreach (DiscDirectoryInfo dinfo in Dinfo.GetDirectories())
{
ExtractDirectory(dinfo, RootPath, PathinISO);
}
foreach (DiscFileInfo finfo in Dinfo.GetFiles())
{
using (Stream FileStr = finfo.OpenRead())
{
using (FileStream Fs = File.Create(RootPath + "\\" + finfo.Name)) // Here you can Set the BufferSize Also e.g. File.Create(RootPath + "\\" + finfo.Name, 4 * 1024)
{
FileStr.CopyTo(Fs, 4 * 1024); // Buffer Size is 4 * 1024 but you can modify it in your code as per your need
}
}
}
}
static void AppendDirectory(string path)
{
try
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
catch (DirectoryNotFoundException Ex)
{
AppendDirectory(Path.GetDirectoryName(path));
}
catch (PathTooLongException Ex)
{
AppendDirectory(Path.GetDirectoryName(path));
}
}
The user selects the folder to extract (.ISO) toExtract. I then use it in the Process.Start() in the background worker. That just seems to open the mounting software and doesn't extract the ISO to the desired folder name.
Thanks in advance for your help.
Or if anyone could give me a batch to extract the ISO instead and to call it from c# passing toExtract and the folder name that would be helpful too.
Thanks
If external Class Libraries are OK!
Then use SevenZipSharp or .NET DiscUtils to extract ISO's...
These two ClassLibraries can manage ISO and Extract them!
For DiscUtils you can find some codes for ISO Management [CDReader Class] at the Link I provided.
But For SevenZipSharp, Please Explore the ClassLibrary source and find the Code to Extract or Google to find it!
To get the Name of the folder just use Path.GetFileNameWithoutExtension((string)ISOFileName) which will return "ISOFile" for an iso named "ISOFile.iso". And then you can use it with your desired path.
UPDATE
Code To Extract ISO Image with DiscUtils :
using DiscUtils;
using DiscUtils.Iso9660;
void ExtractISO(string ISOName, string ExtractionPath)
{
using (FileStream ISOStream = File.Open(ISOName, FileMode.Open))
{
CDReader Reader = new CDReader(ISOStream, true, true);
ExtractDirectory(Reader.Root, ExtractionPath + Path.GetFileNameWithoutExtension(ISOName) + "\\", "");
Reader.Dispose();
}
}
void ExtractDirectory(DiscDirectoryInfo Dinfo, string RootPath, string PathinISO)
{
if (!string.IsNullOrWhiteSpace(PathinISO))
{
PathinISO += "\\" + Dinfo.Name;
}
RootPath += "\\" + Dinfo.Name;
AppendDirectory(RootPath);
foreach (DiscDirectoryInfo dinfo in Dinfo.GetDirectories())
{
ExtractDirectory(dinfo, RootPath, PathinISO);
}
foreach (DiscFileInfo finfo in Dinfo.GetFiles())
{
using (Stream FileStr = finfo.OpenRead())
{
using (FileStream Fs = File.Create(RootPath + "\\" + finfo.Name)) // Here you can Set the BufferSize Also e.g. File.Create(RootPath + "\\" + finfo.Name, 4 * 1024)
{
FileStr.CopyTo(Fs, 4 * 1024); // Buffer Size is 4 * 1024 but you can modify it in your code as per your need
}
}
}
}
static void AppendDirectory(string path)
{
try
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
catch (DirectoryNotFoundException Ex)
{
AppendDirectory(Path.GetDirectoryName(path));
}
catch (PathTooLongException Exx)
{
AppendDirectory(Path.GetDirectoryName(path));
}
}
Use It with Like This :
ExtractISO(ISOFileName, Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\");
Working! Tested By Me!
And Of Course You can always add more Optimization to the code...
This Code is Just a Basic One!
For UDF or for making Windows ISO Files after servicing(DISM) with out needs the above accepted answer is not working for me so i tried this working method with DiscUtils
using DiscUtils;
public static void ReadIsoFile(string sIsoFile, string sDestinationRootPath)
{
Stream streamIsoFile = null;
try
{
streamIsoFile = new FileStream(sIsoFile, FileMode.Open);
DiscUtils.FileSystemInfo[] fsia = FileSystemManager.DetectDefaultFileSystems(streamIsoFile);
if (fsia.Length < 1)
{
MessageBox.Show("No valid disc file system detected.");
}
else
{
DiscFileSystem dfs = fsia[0].Open(streamIsoFile);
ReadIsoFolder(dfs, #"", sDestinationRootPath);
return;
}
}
finally
{
if (streamIsoFile != null)
{
streamIsoFile.Close();
}
}
}
public static void ReadIsoFolder(DiscFileSystem cdReader, string sIsoPath, string sDestinationRootPath)
{
try
{
string[] saFiles = cdReader.GetFiles(sIsoPath);
foreach (string sFile in saFiles)
{
DiscFileInfo dfiIso = cdReader.GetFileInfo(sFile);
string sDestinationPath = Path.Combine(sDestinationRootPath, dfiIso.DirectoryName.Substring(0, dfiIso.DirectoryName.Length - 1));
if (!Directory.Exists(sDestinationPath))
{
Directory.CreateDirectory(sDestinationPath);
}
string sDestinationFile = Path.Combine(sDestinationPath, dfiIso.Name);
SparseStream streamIsoFile = cdReader.OpenFile(sFile, FileMode.Open);
FileStream fsDest = new FileStream(sDestinationFile, FileMode.Create);
byte[] baData = new byte[0x4000];
while (true)
{
int nReadCount = streamIsoFile.Read(baData, 0, baData.Length);
if (nReadCount < 1)
{
break;
}
else
{
fsDest.Write(baData, 0, nReadCount);
}
}
streamIsoFile.Close();
fsDest.Close();
}
string[] saDirectories = cdReader.GetDirectories(sIsoPath);
foreach (string sDirectory in saDirectories)
{
ReadIsoFolder(cdReader, sDirectory, sDestinationRootPath);
}
return;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
it has extracted from a application source ISOReader but modified for my requirements
total source is available at http://www.java2s.com/Open-Source/CSharp_Free_CodeDownload/i/isoreader.zip
Try this:
string Desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
Process.Start("Winrar.exe", string.Format("x {0} {1}",
Desktop + "\\test.rar",
Desktop + "\\SomeFolder"));
That would extract the file test.rar to the folder SomeFolder. You can change the .rar extention to .iso, it'll work the same.
As far as I can see in your current code, there is no command given to extract a file, and no path to the file that has to be extracted. Try this example and let me know if it works =]
P.S. If you'd like to hide the extracting screen, you can set the YourProcessInfo.WindowStyle to ProcessWindowStyle.Hidden.
I hace confrunted recently with this kind of .iso extraction issue. After trying several methods, 7zip did the job for me, you just have to make sure that the latest version of 7zip is installed on your system. Maybe it will help
try
{
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = false;
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
cmd.Start();
cmd.StandardInput.WriteLine("C:");
//Console.WriteLine(cmd.StandardOutput.Read());
cmd.StandardInput.Flush();
cmd.StandardInput.WriteLine("cd C:\\\"Program Files\"\\7-Zip\\");
//Console.WriteLine(cmd.StandardOutput.ReadToEnd());
cmd.StandardInput.Flush();
cmd.StandardInput.WriteLine(string.Format("7z x -y -o{0} {1}", source, copyISOLocation.TempIsoPath));
//Console.WriteLine(cmd.StandardOutput.ReadToEnd());
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
cmd.WaitForExit();
Console.WriteLine(cmd.StandardOutput.ReadToEnd());
}
catch (Exception e)
{
Console.WriteLine(e.Message + "\n" + e.StackTrace);
if (e.InnerException != null)
{
Console.WriteLine(e.InnerException.Message + "\n" + e.InnerException.StackTrace);
}
}

HttpWebResponse hanging up

try
{
responseFile = (HttpWebResponse)requestFile.GetResponse();
}
catch (WebException exRequestFile)
{
MessageBox.Show(exRequestFile.Message);
closeRequest = false;
}
and
if(closeRequest == true) responseFile.Close();
So now my problem:
If i try to download a file, it does so, closes the response. All good.
However, if I type wrong URL (with 404 returned or smth), I can't close the response because it gives me nullreference error. So I close it only when I get a response.
However, after providing wrong URL and not closing response, further tries to download anything result in timeout (even if URL is correct).
Why is that happening and can I resolve it somehow?
EDIT: Full code of class:
public void DownloadAndReplace(string webFile, string sourceFile)
{
var requestFile = (HttpWebRequest)WebRequest.Create(webFile);
var requestMD5 = (HttpWebRequest)WebRequest.Create(webFile + ".md5");
var requestSHA = (HttpWebRequest)WebRequest.Create(webFile + ".sha");
bool closeRequest = true;
_location = sourceFile + "\\" + OriginalFileName(webFile);
requestFile.Method = "HEAD";
requestFile.Timeout = 2000;
HttpWebResponse responseFile = null;
HttpWebResponse responseMD5 = null;
HttpWebResponse responseSHA = null;
try
{
responseFile = (HttpWebResponse)requestFile.GetResponse();
}
catch (WebException exRequestFile)
{
MessageBox.Show(exRequestFile.Message);
closeRequest = false;
}
if (!File.Exists(_location) || responseFile.LastModified > File.GetLastWriteTime(_location))
{
downloadFile(webFile, _location);
if (_controlsRef.chooseMD5.Checked)
{
try
{
responseMD5 = (HttpWebResponse)requestMD5.GetResponse();
downloadFile(webFile + ".md5", _location);
responseMD5.Close();
}
catch (WebException exRequestFile)
{
MessageBox.Show(exRequestFile.Message + " " + webFile + ".md5");
}
}
else if (_controlsRef.chooseSHA1.Checked)
{
try
{
responseSHA = (HttpWebResponse)requestSHA.GetResponse();
downloadFile(webFile + ".sha", _location);
responseSHA.Close();
}
catch (WebException exRequestFile)
{
MessageBox.Show(exRequestFile.Message + " " + webFile + ".sha");
}
}
}
else MessageBox.Show("Newest version");
if(closeRequest == true) responseFile.Close();
public void downloadFile(string urlAddress, string location)
{
_fileHasher = new HashFile(_controlsRef);
using (var downloadClient = new WebClient())
{
downloadClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(Completed);
downloadClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
Uri URL = new Uri(urlAddress);
if (location == Environment.GetFolderPath(Environment.SpecialFolder.Desktop))
{
location = location + "\\" + OriginalFileName(urlAddress);
this._location = location;
}
else location = _location;
_downloadStopWatch.Start();
if (File.Exists(location))
{
File.Delete(location);
}
if (_isFile == true)
{
try
{
downloadClient.DownloadFileAsync(URL, location);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
_isFile = false;
}
}
}
}
private string OriginalFileName(string urlAddress)
{
var requestFile = (HttpWebRequest)WebRequest.Create(urlAddress);
requestFile.Method = "HEAD";
HttpWebResponse responseFile = null;
string originalFileName = "";
try
{
responseFile = (HttpWebResponse)requestFile.GetResponse();
}
catch (WebException exResponse)
{
MessageBox.Show(exResponse.Message);
_isFile = false;
}
if (_isFile == true)
{
int segmentLenght = responseFile.ResponseUri.Segments.Length;
originalFileName = responseFile.ResponseUri.Segments[segmentLenght - 1];
responseFile.Close();
}
return originalFileName;
}
To further clarify:
I provide URL for existing file 1. All is ok.
I provide URL for existing file 2. All is ok.
I provide URL for non-exisitng file 3. It throws me an 404 error.
I provide URL for existing file 4. I get program hangup and timeout.
Wrap your HttpWebResponse inside a using statement so that the object can be disposed correctly.
Something like this:
try
{
using(responseFile = (HttpWebResponse)requestFile.GetResponse())
{
...your code...
}
}
catch (WebException exRequestFile)
{
MessageBox.Show(exRequestFile.Message);
closeRequest = false;
}
"using" reference: https://msdn.microsoft.com/en-us/library/yh598w02.aspx

How to know when a method finish in controller

I have a problem with this method, i want to return a PDF file and when the method it's over i want to delete de file from the directory.
public ActionResult DescargaPdfCompara(string id)
{
var rutaPdf = string.Empty;
var type = "application/pdf";
try
{
DateTime ahora = DateTime.Now;
var numeroAleatorio = new Random();
int numeroRandomico = numeroAleatorio.Next(100000000, 1000000000);
string Ruta = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Reportes\" + Convert.ToString(ahora.Year + ahora.Month + ahora.Day + ahora.Hour + ahora.Minute + ahora.Second + numeroRandomico) + ".pdf");
var result = SimuModel.ObtenerSabanaReporteComparativo(id);
var resumen = SimuModel.ObtenerPreExcel(result);
SimuModel.GenerarPdfCompa(result, resumen, Ruta);
rutaPdf = Ruta;
return File(rutaPdf, type);
}
catch (Exception e)
{
throw e;
}
finally
{
System.IO.File.Delete(rutaPdf);
}
}
In the finally i delete the file but i got an error because the method can't find the file, for some reason the method delete the file before return it.
PD: Sorry for my english, i'm from Chile.
Thanks fro your answers!
You can use System.IO.File.ReadAllBytes to read all the file contents to memory, then delete the file and return the contents with another overload of Controller.File method:
public ActionResult GetFile()
{
var fileName = Path.GetTempFileName();
System.IO.File.WriteAllText(fileName, "Hola, Chile!");
var bytes = System.IO.File.ReadAllBytes(fileName);
System.IO.File.Delete(fileName);
return File(bytes, "text/plain", "file.txt");
}
Change return type ContentResult
remove finally section.
public ContentResult DescargaPdfCompara(string id)
{
var rutaPdf = string.Empty;
var type = "application/pdf";
try
{
DateTime ahora = DateTime.Now;
var numeroAleatorio = new Random();
int numeroRandomico = numeroAleatorio.Next(100000000, 1000000000);
string Ruta = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Reportes\" + Convert.ToString(ahora.Year + ahora.Month + ahora.Day + ahora.Hour + ahora.Minute + ahora.Second + numeroRandomico) + ".pdf");
var result = SimuModel.ObtenerSabanaReporteComparativo(id);
var resumen = SimuModel.ObtenerPreExcel(result);
SimuModel.GenerarPdfCompa(result, resumen, Ruta);
rutaPdf = Ruta;
return Content(rutaPdf, type);
}
catch (Exception e)
{
throw e;
}
}

C# Upload whole directory using FTP

What I'm trying to do is to upload a website using FTP in C# (C Sharp). So I need to upload all files and folders within a folder, keeping its structure. I'm using this FTP class: http://www.codeproject.com/Tips/443588/Simple-Csharp-FTP-Class for the actual uploading.
I have come to the conclusion that I need to write a recursive method that goes through every sub-directory of the main directory and upload all files and folders in it. This should make an exact copy of my folder to the FTP. Problem is... I have no clue how to write a method like that. I have written recursive methods before but I'm new to the FTP part.
This is what I have so far:
private void recursiveDirectory(string directoryPath)
{
string[] filePaths = null;
string[] subDirectories = null;
filePaths = Directory.GetFiles(directoryPath, "*.*");
subDirectories = Directory.GetDirectories(directoryPath);
if (filePaths != null && subDirectories != null)
{
foreach (string directory in subDirectories)
{
ftpClient.createDirectory(directory);
}
foreach (string file in filePaths)
{
ftpClient.upload(Path.GetDirectoryName(directoryPath), file);
}
}
}
But its far from done and I don't know how to continue. I'm sure more than me needs to know this! Thanks in advance :)
Ohh and... It would be nice if it reported its progress too :) (I'm using a progress bar)
EDIT:
It might have been unclear... How do I upload a directory including all sub-directories and files with FTP?
Problem Solved! :)
Alright so I managed to write the method myslef. If anyone need it feel free to copy:
private void recursiveDirectory(string dirPath, string uploadPath)
{
string[] files = Directory.GetFiles(dirPath, "*.*");
string[] subDirs = Directory.GetDirectories(dirPath);
foreach (string file in files)
{
ftpClient.upload(uploadPath + "/" + Path.GetFileName(file), file);
}
foreach (string subDir in subDirs)
{
ftpClient.createDirectory(uploadPath + "/" + Path.GetFileName(subDir));
recursiveDirectory(subDir, uploadPath + "/" + Path.GetFileName(subDir));
}
}
It works very well :)
I wrote an FTP classe and also wrapped it in a WinForms user control. You can see my code in the article An FtpClient Class and WinForm Control.
I wrote a reusable class to upload entire directory to an ftp site on windows server, the program also renames the old version of that folder (i use it to upload my windows service program to the server).
maybe some need this:
class MyFtpClient
{
protected string FtpUser { get; set; }
protected string FtpPass { get; set; }
protected string FtpServerUrl { get; set; }
protected string DirPathToUpload { get; set; }
protected string BaseDirectory { get; set; }
public MyFtpClient(string ftpuser, string ftppass, string ftpserverurl, string dirpathtoupload)
{
this.FtpPass = ftppass;
this.FtpUser = ftpuser;
this.FtpServerUrl = ftpserverurl;
this.DirPathToUpload = dirpathtoupload;
var spllitedpath = dirpathtoupload.Split('\\').ToArray();
// last index must be the "base" directory on the server
this.BaseDirectory = spllitedpath[spllitedpath.Length - 1];
}
public void UploadDirectory()
{
// rename the old folder version (if exist)
RenameDir(BaseDirectory);
// create a parent folder on server
CreateDir(BaseDirectory);
// upload the files in the most external directory of the path
UploadAllFolderFiles(DirPathToUpload, BaseDirectory);
// loop trough all files in subdirectories
foreach (string dirPath in Directory.GetDirectories(DirPathToUpload, "*",
SearchOption.AllDirectories))
{
// create the folder
CreateDir(dirPath.Substring(dirPath.IndexOf(BaseDirectory), dirPath.Length - dirPath.IndexOf(BaseDirectory)));
Console.WriteLine(dirPath.Substring(dirPath.IndexOf(BaseDirectory), dirPath.Length - dirPath.IndexOf(BaseDirectory)));
UploadAllFolderFiles(dirPath, dirPath.Substring(dirPath.IndexOf(BaseDirectory), dirPath.Length - dirPath.IndexOf(BaseDirectory))
}
}
private void UploadAllFolderFiles(string localpath, string remotepath)
{
string[] files = Directory.GetFiles(localpath);
// get only the filenames and concat to remote path
foreach (string file in files)
{
// full remote path
var fullremotepath = remotepath + "\\" + Path.GetFileName(file);
// local path
var fulllocalpath = Path.GetFullPath(file);
// upload to server
Upload(fulllocalpath, fullremotepath);
}
}
public bool CreateDir(string dirname)
{
try
{
WebRequest request = WebRequest.Create("ftp://" + FtpServerUrl + "/" + dirname);
request.Method = WebRequestMethods.Ftp.MakeDirectory;
request.Proxy = new WebProxy();
request.Credentials = new NetworkCredential(FtpUser, FtpPass);
using (var resp = (FtpWebResponse)request.GetResponse())
{
if (resp.StatusCode == FtpStatusCode.PathnameCreated)
{
return true;
}
else
{
return false;
}
}
}
catch
{
return false;
}
}
public void Upload(string filepath, string targetpath)
{
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential(FtpUser, FtpPass);
client.Proxy = null;
var fixedpath = targetpath.Replace(#"\", "/");
client.UploadFile("ftp://" + FtpServerUrl + "/" + fixedpath, WebRequestMethods.Ftp.UploadFile, filepath);
}
}
public bool RenameDir(string dirname)
{
var path = "ftp://" + FtpServerUrl + "/" + dirname;
string serverUri = path;
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.Rename;
request.Proxy = null;
request.Credentials = new NetworkCredential(FtpUser, FtpPass);
// change the name of the old folder the old folder
request.RenameTo = DateTime.Now.ToString("yyyyMMddHHmmss");
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
using (var resp = (FtpWebResponse)request.GetResponse())
{
if (resp.StatusCode == FtpStatusCode.FileActionOK)
{
return true;
}
else
{
return false;
}
}
}
catch
{
return false;
}
}
}
Create an instance of that class:
static void Main(string[] args)
{
MyFtpClientftp = new MyFtpClient(ftpuser, ftppass, ftpServerUrl, #"C:\Users\xxxxxxxxxxx");
ftp.UploadDirectory();
Console.WriteLine("DONE");
Console.ReadLine();
}
Unless you're doing this for fun or self-improvement, use a commercial module. I can recommend one from Chilkat, but I'm sure there are others.
Note: I'm pretty sure this does answer the stated problem, What I'm trying to do is to upload a website using FTP in C# (C Sharp).

Categories

Resources