نحوه کار با ftp - بخش اول
نویسنده: بهمن آبادی
تاریخ: ۱۳۹۲/۰۲/۱۱ ۱۹:۵۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
<add key="FtpAddress" value="ftp://ftp.dotnetips.info" /> <add key="FtpUser" value="uploadcenter" /> <add key="FtpPass" value="123123" /> <add key="FolderPath" value="~/Upload/" />
using System.Net;
using System.IO;
using System.Configuration;
public class FtpHelper
{
public FtpHelper()
{
//Default Value Set From Application
_hostname = ConfigurationManager.AppSettings.GetValues("FtpAddress")[0];
_username = ConfigurationManager.AppSettings.GetValues("FtpUser")[0];
_password = ConfigurationManager.AppSettings.GetValues("FtpPass")[0];
}
#region "Properties"
private string _hostname;
/// <summary>
/// Hostname
/// </summary>
/// <value></value>
/// <remarks>Hostname can be in either the full URL format
/// ftp://ftp.myhost.com or just ftp.myhost.com
/// </remarks>
public string Hostname
{
get
{
if (_hostname.StartsWith("ftp://"))
{
return _hostname;
}
else
{
return "ftp://" + _hostname;
}
}
set
{
_hostname = value;
}
}
private string _username;
/// <summary>
/// Username property
/// </summary>
/// <value></value>
/// <remarks>Can be left blank, in which case 'anonymous' is returned</remarks>
public string Username
{
get
{
return (_username == "" ? "anonymous" : _username);
}
set
{
_username = value;
}
}
private string _password;
public string Password
{
get
{
return _password;
}
set
{
_password = value;
}
}
#endregion
}using System.Net; using System.IO;
public static bool Upload(string fileUrl)
{
if (File.Exists(fileUrl))
{
FtpHelper ftpClient = new FtpHelper();
string ftpUrl = ftpClient.Hostname + System.IO.Path.GetFileName(fileUrl);
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpUrl);
ftp.Credentials = new NetworkCredential(ftpClient.Username, ftpClient.Password);
ftp.KeepAlive = true;
ftp.UseBinary = true;
ftp.Timeout = 3600000;
ftp.KeepAlive = true;
ftp.Method = WebRequestMethods.Ftp.UploadFile;
const int bufferLength = 102400;
byte[] buffer = new byte[bufferLength];
int readBytes = 0;
//open file for reading
using (FileStream fs = File.OpenRead(fileUrl))
{
try
{
//open request to send
using (Stream rs = ftp.GetRequestStream())
{
do
{
readBytes = fs.Read(buffer, 0, bufferLength);
fs.Write(buffer, 0, readBytes);
} while (!(readBytes < bufferLength));
rs.Close();
}
}
catch (Exception)
{
//Optional Alert for Exeption To Application Layer
//throw (new ApplicationException("بارگذاری فایل با خطا رو به رو شد"));
}
finally
{
//ensure file closed
//fs.Close();
}
}
ftp = null;
return true;
}
return false;
}.locals init ([0] class [mscorlib]System.IO.TextWriter w)
IL_0000: ldstr "log.txt"
IL_0005: call class [mscorlib]System.IO.StreamWriter
[mscorlib]System.IO.File::CreateText(string)
IL_000a: stloc.0
.try
{
IL_000b: ldloc.0
IL_000c: ldstr "This is line one"
IL_0011: callvirt instance void [mscorlib]
System.IO.TextWriter::WriteLine(string)
IL_0016: leave.s IL_0022
} // end .try
finally
{
IL_0018: ldloc.0
IL_0019: brfalse.s IL_0021
IL_001b: ldloc.0
IL_001c: callvirt instance void [mscorlib]
System.IDisposable::Dispose()
IL_0021: endfinally
} // end handlerماخذ
زمانیکه از using statement استفاده میکنید، خود کامپایلر try/finally رو اضافه میکنه. یعنی قسمت close الان بهش نیازی نیست چون استریم مورد استفاده حتما در اینجا dispose میشه.
The remote server returned an error: (425) Can't open data connection
WinSCP.SessionRemoteException: Lost connection. Timeout detected. (data connection) Copying files to remote side failed. Copying files to remote side failed.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.diagnostics>
<trace autoflush="true" />
<sources>
<source name="System.Net">
<listeners>
<add name="MyTraceFile"/>
</listeners>
</source>
</sources>
<sharedListeners>
<add
name="MyTraceFile"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="System.Net.trace.log"
/>
</sharedListeners>
<switches>
<add name="System.Net" value="Verbose" />
</switches>
</system.diagnostics>
</configuration>