将.log文件从本地计算机上传到FTP

时间:2014-01-09 05:27:05

标签: c#

对于Cron服务,我在本地计算机上的.log文件中记录错误,然后我将其上载到ftp上。所以我的问题是在ftp上传文件后我得到了不完整和不正确的日志文件格式,就像在本地机器上一样。任何人都可以帮助我,让我知道我失踪的地方。

示例登录本地计算机:

时间戳:1/8/2014 5:50:14 PM

候选人电邮:aabc00@gmail.com

状态:成功:已创建

同样登录ftp:

te电子邮件:aabc00@gmail.com

状态:成功:已创建

我正在尝试此代码:

using (FileStream fileStream = new FileInfo(Convert.ToString(ConfigurationManager.AppSettings["DestinationLocation"]) + @"\" + fileName).Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                int bufferLength = 2048;
                byte[] buffer = new byte[bufferLength];

                using (Stream uploadStream = request.GetRequestStream())
                {
                    int contentLength = fileStream.Read(buffer, 0, bufferLength);

                    while (contentLength != 0)
                    {
                        uploadStream.Write(buffer, 0, bufferLength);
                        contentLength = fileStream.Read(buffer, 0, bufferLength);
                    }
                    fileStream.Close();
                    uploadStream.Close();
                }
            }

1 个答案:

答案 0 :(得分:0)

请试试这个。您的代码不考虑读取信息的大小,看起来总是保存最小的读取。

using (FileStream fileStream = new FileInfo(Convert.ToString(ConfigurationManager.AppSettings["DestinationLocation"]) + @"\" + fileName).Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    {  
        byte[] buffer = new byte[fileStream.Length];
        int numBytesToRead = (int)fileStream.Length;
        int numBytesRead = 0;

        if (numBytesToRead > 0) 
        {       
            // get all file information in to the buffer
            while (numBytesToRead > 0)
            {
                int n = fileStream.Read(buffer, numBytesRead, numBytesToRead);

                if (n == 0)
                    break;

                numBytesRead += n;
                numBytesToRead -= n;
            }

            // now write that data to the file      
            using (Stream uploadStream = request.GetRequestStream())
            {
                uploadStream.Write(buffer, 0, buffer.Length);
            }
        }
    }