本文整理汇总了C#中FtpClient.OpenWrite方法的典型用法代码示例。如果您正苦于以下问题:C# FtpClient.OpenWrite方法的具体用法?C# FtpClient.OpenWrite怎么用?C# FtpClient.OpenWrite使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类FtpClient
的用法示例。
在下文中一共展示了FtpClient.OpenWrite方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: UploadFile
public static void UploadFile(string ftpHost, string username, string password, string filepathToUpload, string fileToWrite)
{
FtpClient chipbox = new FtpClient();
chipbox.Host = ftpHost;
chipbox.Credentials = new NetworkCredential(username, password);
Stream chipboxDosya = chipbox.OpenWrite(fileToWrite);
FileStream dosya = new FileStream(filepathToUpload, FileMode.Open);
try
{
int bufferSize = 8192;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = dosya.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
chipboxDosya.Write(buffer, 0, readCount);
readCount = dosya.Read(buffer, 0, bufferSize);
}
}
finally
{
dosya.Close();
chipboxDosya.Close();
}
}
示例2: OpenWrite
public static void OpenWrite() {
using (FtpClient conn = new FtpClient()) {
conn.Host = "localhost";
conn.Credentials = new NetworkCredential("ftptest", "ftptest");
using (Stream ostream = conn.OpenWrite("/full/or/relative/path/to/file")) {
try {
// istream.Position is incremented accordingly to the writes you perform
}
finally {
ostream.Close();
}
}
}
}
示例3: Send
private void Send(FileItem item, AutoExportPluginConfig configData)
{
try
{
var filename = item.FileName;
configData.IsRedy = false;
configData.IsError = false;
var conf = new FtpPluginViewModel(configData);
var outfile = Path.Combine(Path.GetTempPath(), Path.GetFileName(filename));
outfile = AutoExportPluginHelper.ExecuteTransformPlugins(item, configData, outfile);
using (FtpClient conn = new FtpClient())
{
conn.Host = conf.Server;
conn.Credentials = new NetworkCredential(conf.User, conf.Pass);
if (!string.IsNullOrWhiteSpace(conf.ServerPath))
conn.SetWorkingDirectory(conf.ServerPath);
using (Stream ostream = conn.OpenWrite(Path.GetFileName(outfile)))
{
try
{
var data = File.ReadAllBytes(outfile);
ostream.Write(data, 0, data.Length);
}
finally
{
ostream.Close();
}
}
}
// remove unused file
if (outfile != item.FileName)
{
PhotoUtils.WaitForFile(outfile);
File.Delete(outfile);
}
}
catch (Exception exception)
{
Log.Error("Error senf ftp file", exception);
configData.IsError = true;
configData.Error = exception.Message;
}
configData.IsRedy = true;
}
示例4: Main
static void Main(string[] args)
{
FtpClient ftpClient = new FtpClient
{ Credentials = new NetworkCredential("[email protected]", "A1bl1m1v"),
Host = "adolgushin.com" };
using (Stream openWrite = ftpClient.OpenWrite("/porn/new.txt"))
{
byte[] buffer = new byte[8192];
using (FileStream fileStream = File.OpenRead(@"c:\temp\tracked\new.txt"))
{
do
{
int length = fileStream.Read(buffer, 0, 8192);
if (length <= 0)
break;
openWrite.Write(buffer, 0, length);
} while (true);
}
openWrite.Flush();
openWrite.Close();
}
}
示例5: UploadFile
public string UploadFile(HttpPostedFileBase file)
{
string destinationFile = _folder + ((_folder == "/") ? "" : "/") + Path.GetFileName(file.FileName);
using (var ftpClient = new FtpClient())
{
ftpClient.Host = _host;
ftpClient.Port = 21;
ftpClient.DataConnectionType = FtpDataConnectionType.EPSV;
ftpClient.Credentials = new NetworkCredential(_username, _password);
ftpClient.Connect();
// ftpClient.CreateDirectory("/test");
ftpClient.SetWorkingDirectory(_folder);
byte[] buf = new byte[8192];
int read = 0;
using (var remoteStream = ftpClient.OpenWrite(destinationFile))
{
using (var localStream = new MemoryStream())
{
// Copy the file data from the posted file into a MemoryStream
file.InputStream.CopyTo(localStream);
// Reset position of stream after copy, otherwise we get zero-length files...
localStream.Position = 0;
while ((read = localStream.Read(buf, 0, buf.Length)) > 0)
{
remoteStream.Write(buf, 0, read);
}
}
}
ftpClient.Disconnect();
return Path.GetFileName(destinationFile);
}
}
示例6: TransferFile
private void TransferFile(string pvtFileName)
{
Event clsEvent = new Event();
try
{
if (!string.IsNullOrEmpty(pvtFileName))
{
if (string.IsNullOrEmpty(mclsAyalaDetails.FTPIPAddress))
{
clsEvent.AddEventLn("Cannot transfer file " + pvtFileName + ". FTP IPAddress is empty Automatic File transfer is disabled.", true);
return;
}
else
clsEvent.AddEventLn("Transferring " + pvtFileName + " to " + mclsAyalaDetails.FTPIPAddress, true);
}
else
{
clsEvent.AddEventLn("Cannot transfer an blank file.", true); return;
}
int intPort = 21;
if (System.Configuration.ConfigurationManager.AppSettings["VersionFTPPort"] != null)
{
try { intPort = int.Parse(System.Configuration.ConfigurationManager.AppSettings["VersionFTPPort"]); }
catch { }
}
FtpClient ftpClient = new FtpClient();
ftpClient.Host = mclsAyalaDetails.FTPIPAddress;
ftpClient.Port = intPort;
ftpClient.Credentials = new NetworkCredential(mclsAyalaDetails.FTPUsername, mclsAyalaDetails.FTPPassword);
IEnumerable<FtpListItem> lstFtpListItem = ftpClient.GetListing(mclsAyalaDetails.FTPDirectory, FtpListOption.Modify | FtpListOption.Size);
bool bolIsFileExist = false;
clsEvent.AddEventLn("Checking file if already exist...", true);
try
{
foreach (FtpListItem ftpListItem in lstFtpListItem)
{
if (ftpListItem.Name.ToUpper() == Path.GetFileName(pvtFileName).ToUpper())
{ bolIsFileExist = true; break; }
}
}
catch (Exception excheck)
{
clsEvent.AddEventLn("checking error..." + excheck.Message, true);
}
if (bolIsFileExist)
{
clsEvent.AddEventLn("exist...", true);
clsEvent.AddEventLn("uploading now...", true);
}
else
{
clsEvent.AddEventLn("does not exist...", true);
clsEvent.AddEventLn("uploading now...", true);
}
using (var fileStream = File.OpenRead(pvtFileName))
using (var ftpStream = ftpClient.OpenWrite(string.Format("{0}/{1}", Path.GetFileName(pvtFileName), Path.GetFileName(pvtFileName))))
{
var buffer = new byte[8 * 1024];
int count;
while ((count = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
ftpStream.Write(buffer, 0, count);
}
clsEvent.AddEventLn("Upload Complete: TotalBytes: " + buffer.ToString(), true);
}
ftpClient.Disconnect();
ftpClient.Dispose();
ftpClient = null;
clsEvent.AddEventLn("Done.", true);
}
catch (Exception ex)
{
clsEvent.AddEventLn("Error encountered: " + ex.Message, true);
throw new IOException("Sales file is not sent to RLC server. Please contact your POS vendor");
}
}
示例7: UploadBackupFile
private void UploadBackupFile(FtpClient ftpClient, string ftpBackupPath, string backupFilePath)
{
Stream ftpBackupFile;
long totalBytesWritten = 0;
var backupFilename = Path.GetFileName(backupFilePath);
var ftpBackupFilePath = ftpBackupPath + "/" + backupFilename;
if (ftpClient.FileExists(ftpBackupFilePath))
{
var ftpBackupFileSize = ftpClient.GetFileSize(ftpBackupFilePath);
totalBytesWritten = ftpBackupFileSize;
ftpBackupFile = ftpClient.OpenAppend(ftpBackupPath + "/" + backupFilename, FtpDataType.Binary);
}
else
{
ftpBackupFile = ftpClient.OpenWrite(ftpBackupPath + "/" + backupFilename, FtpDataType.Binary);
}
try
{
using (var backupFile = File.OpenRead(backupFilePath))
{
int bytesRead;
var totalBytes = backupFile.Length;
var bytesWrittenLogPoint = 0.1;
var buffer = new byte[4096];
_log.Info(string.Format("Uploading {0} ({1:N0} bytes)...", backupFilename, totalBytes));
if (totalBytesWritten > 0)
backupFile.Seek(totalBytesWritten, SeekOrigin.Begin);
while ((bytesRead = backupFile.Read(buffer, 0, buffer.Length)) > 0)
{
ftpBackupFile.Write(buffer, 0, bytesRead);
totalBytesWritten += bytesRead;
var writtenBytesPercentage = ((float)totalBytesWritten / totalBytes);
if (writtenBytesPercentage >= bytesWrittenLogPoint)
{
_log.Info(
string.Format(
"Backup file upload progress: {0:P} ({1:N0} bytes) of {2}.",
writtenBytesPercentage,
totalBytesWritten,
backupFilename));
bytesWrittenLogPoint += 0.1;
}
}
}
}
finally
{
ftpBackupFile.Dispose();
}
}
示例8: AttachFile
private void AttachFile()
{
try
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = false;
if (ofd.ShowDialog() == DialogResult.OK)
{
string fileName = System.IO.Path.GetFileName(ofd.FileName);
string filePath = System.IO.Path.GetFullPath(ofd.FileName);
string strNewFileName = SalesTransactionItemDetails.TransactionID.ToString() + "_" + SalesTransactionItemDetails.TransactionItemsID + "_" + fileName;
Data.SalesTransactionItemAttachmentDetails clsDetails = new Data.SalesTransactionItemAttachmentDetails();
clsDetails.TransactionItemAttachmentsID = 0;
clsDetails.TransactionItemsID = SalesTransactionItemDetails.TransactionItemsID;
clsDetails.TransactionID = SalesTransactionItemDetails.TransactionID;
clsDetails.OrigFileName = fileName;
clsDetails.FileName = strNewFileName;
clsDetails.UploadedByName = CashierName;
clsDetails.CreatedOn = DateTime.Now;
clsDetails.LastModified = clsDetails.CreatedOn;
Data.SalesTransactionItemAttachments clsSalesTransactionItemAttachments = new Data.SalesTransactionItemAttachments();
clsSalesTransactionItemAttachments.Insert(clsDetails);
clsSalesTransactionItemAttachments.CommitAndDispose();
try
{
string strServer = "127.0.0.1";
if (System.Configuration.ConfigurationManager.AppSettings["VersionFTPIPAddress"] != null)
{
try { strServer = System.Configuration.ConfigurationManager.AppSettings["VersionFTPIPAddress"].ToString(); }
catch { }
}
int intPort = 21;
if (System.Configuration.ConfigurationManager.AppSettings["VersionFTPPort"] != null)
{
try { intPort = int.Parse(System.Configuration.ConfigurationManager.AppSettings["VersionFTPPort"]); }
catch { }
}
string strUserName = "ftprbsuser";
string strPassword = "ftprbspwd";
string strFTPDirectory = "attachment";
string destinationDirectory = Application.StartupPath;
//string strConstantRemarks = "Please contact your system administrator immediately.";
FtpClient ftpClient = new FtpClient();
ftpClient.Host = strServer;
ftpClient.Port = intPort;
ftpClient.Credentials = new NetworkCredential(strUserName, strPassword);
IEnumerable<FtpListItem> lstFtpListItem = ftpClient.GetListing(strFTPDirectory, FtpListOption.Modify | FtpListOption.Size);
Event clsEvent = new Event();
bool bolIsFileExist = false;
clsEvent.AddEventLn("Checking file if already exist...", true);
try
{
foreach (FtpListItem ftpListItem in lstFtpListItem)
{
if (ftpListItem.Name.ToUpper() == Path.GetFileName(strNewFileName).ToUpper())
{ bolIsFileExist = true; break; }
}
}
catch (Exception excheck)
{
clsEvent.AddEventLn("checking error..." + excheck.Message, true);
}
if (bolIsFileExist)
{
clsEvent.AddEventLn("exist...", true);
clsEvent.AddEventLn("uploading now...", true);
}
else
{
clsEvent.AddEventLn("does not exist...", true);
clsEvent.AddEventLn("uploading now...", true);
}
using (var fileStream = File.OpenRead(filePath))
using (var ftpStream = ftpClient.OpenWrite(string.Format("{0}/{1}", strFTPDirectory, Path.GetFileName(strNewFileName))))
{
var buffer = new byte[8 * 1024];
int count;
while ((count = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
ftpStream.Write(buffer, 0, count);
}
clsEvent.AddEventLn("Upload Complete: TotalBytes: " + buffer.ToString(), true);
}
ftpClient.Disconnect();
//.........这里部分代码省略.........
示例9: uploadFTP
/// <summary>
/// Uploads a file to FTP
/// </summary>
/// <param name="localFileName">Local file to upload</param>
/// <param name="uploadPath">URI of the file to upload</param>
/// <param name="silent"></param>
/// <param name="ignoreError"></param>
/// <param name="errorActions"></param>
public static void uploadFTP(string Host, string localFileName, string serverPath, NetworkCredential Credentials, bool silent = false, bool ignoreError = false, string[] errorActions = null)
{
try
{
int bufferSize = 8192;
FtpClient FTP = new FtpClient();
FTP.ValidateCertificate += FTPClient_ValidateCertificate;
FTP.Host = Host;
FTP.Credentials = Credentials;
FTP.Connect();
if (!silent) Logging.logMessage("Connected to: " + Host, 1);
if (!FTP.DirectoryExists(serverPath))
{
Logging.logMessage("Created directory on server: " + serverPath);
FTP.CreateDirectory(serverPath);
}
FileStream localFile = new FileStream(localFileName, FileMode.OpenOrCreate);
byte[] Buffer = new byte[bufferSize];
Stream writeStream = FTP.OpenWrite(serverPath + Path.GetFileName(localFileName), FtpDataType.Binary);
int bytesSent = localFile.Read(Buffer, 0, bufferSize);
while (bytesSent != 0)
{
writeStream.Write(Buffer, 0, bytesSent);
bytesSent = localFile.Read(Buffer, 0, bufferSize);
}
localFile.Close();
writeStream.Close();
FTP.Dispose();
if (!silent) Logging.logMessage("Disconnedted from FTP server", 1);
}
catch (Exception e)
{
if (!ignoreError) Logging.showError("Failed to upload file via FTP:" + Environment.NewLine + e.ToString(), errorActions);
}
}
示例10: UploadFile
/// <summary>
/// Send file to remote. Only FTP supported at present
/// </summary>
/// <param name="file"></param>
/// <param name="source"></param>
/// <returns></returns>
public static bool UploadFile(Uri file, string source)
{
try
{
string[] userInfo = file.UserInfo.Split(new[] { ':' });
if (userInfo.Length != 2)
{
Logger.Warn("No login information in URL!");
return false;
}
using (var cl = new FtpClient(userInfo[0], userInfo[1], file.Host))
{
string remoteFile = file.PathAndQuery;
// Check for existence
if (!File.Exists(source))
return false;
long size = new FileInfo(source).Length;
using (FtpDataStream chan = cl.OpenWrite(remoteFile))
{
using (var stream = new FileStream(source, FileMode.Open))
{
using (var reader = new BinaryReader(stream))
{
var buf = new byte[cl.SendBufferSize];
int read;
long total = 0;
while ((read = reader.Read(buf, 0, buf.Length)) > 0)
{
total += read;
chan.Write(buf, 0, read);
Logger.DebugFormat("\rUploaded: {0}/{1} {2:p2}",
total, size, (total / (double)size));
}
}
}
// when Dispose() is called on the chan object, the data channel
// stream will automatically be closed
}
// when Dispose() is called on the cl object, a logout will
// automatically be performed and the socket will be closed.
}
}
catch (Exception e)
{
Logger.Warn("Exception uploading file:" + e.Message);
return false;
}
return true;
}
示例11: UploadFile
/// <summary>
/// The upload file.
/// </summary>
/// <param name="client">
/// The client.
/// </param>
/// <param name="filePath">
/// The file path.
/// </param>
/// <param name="cnt">
/// The cnt.
/// </param>
private void UploadFile(FtpClient client, string filePath, int cnt)
{
string uploadMessage = string.Format("Uploading {0} to {1}", filePath, client.Host);
WriteVerbose(uploadMessage);
var myprogress = new ProgressRecord(cnt, uploadMessage, "Progress:");
using (FileStream fileStream = File.OpenRead(filePath))
using (Stream ftpStream = client.OpenWrite(Path.GetFileName(filePath)))
{
var buffer = new byte[8*1024];
int count;
long total = 0;
long size = fileStream.Length;
while ((count = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
ftpStream.Write(buffer, 0, count);
myprogress.PercentComplete = (int) (total/size)*100;
WriteProgress(myprogress);
total += count;
}
}
myprogress.PercentComplete = 100;
myprogress.StatusDescription = "Complete";
WriteProgress(myprogress);
}
示例12: ftpUploadFile
private static void ftpUploadFile(FtpClient client, string ftpDirectory, DownloadedFile file, bool deleteOriginalFile, bool insertAuditRecord)
{
if (client.IsConnected)
{
using (var fileStream = File.OpenRead(file.finalPath))
{
using (var ftpStream = client.OpenWrite(string.Format("{0}/{1}", ftpDirectory, file.name)))
{
try
{
//Copyies the file to the ftp.
fileStream.CopyTo(ftpStream);
}
catch (Exception e)
{
appendToBody(String.Format("Exception CopyTo ftp...{0}", e));
}
}
}
if (insertAuditRecord) {
insertToDatabase(file);
}
if (deleteOriginalFile)
{
File.Delete(file.finalPath);
}
}
else
{
Console.WriteLine("FTP doesn't have a connection, file upload failed");
}
}
示例13: MoveFile
private void MoveFile(IList<LogEntity> logs)
{
//FtpTrace.AddListener(new EventLogTraceListener("log上传"));
using (var conn = new FtpClient())
{
var serverConfig = ConfigureManager.Logsever;
conn.Host = serverConfig.IP;
conn.Credentials = new NetworkCredential(serverConfig.UserName, serverConfig.Pwd);
conn.DataConnectionType = FtpDataConnectionType.AutoPassive;
foreach (var logEntity in logs)
{
LogManager.Instance.Log.Info(string.Format("开始上传log:{0}", logEntity.UpLoadPath));
var path = Path.GetFileName(logEntity.UpLoadPath);
if (logEntity.Content == null)
{
LogManager.Instance.Log.Info(string.Format("log:{0} 流内容为空", logEntity.LogId));
continue;
}
LogManager.Instance.Log.Info(string.Format("开始读流"));
using (var stream = conn.OpenWrite(path))
{
stream.Write(logEntity.Content, 0, logEntity.Content.Length);
}
LogManager.Instance.Log.Info(string.Format("上传结束log:{0},log大小为:{1}", conn.Host,
logEntity.Content.Length));
logEntity.Success = true;
}
LogManager.Instance.Log.Info("上传结束!");
}
}