C# .dat将文件上传到 FTP,努力为我的控制台应用程序找到工作示例

本文关键字:控制台 我的 应用程序 工作 文件 dat FTP 努力 | 更新日期: 2023-09-27 18:36:40

好的,所以我想使用 C# 2010 将文件发送到我的 drivehq ftp 服务器 我已经在我的控制台应用程序中尝试了多普尔考试 有些已经上传了文件,但总是损坏 其他不起作用 有人可以帮我如何将.dat文件上传到ftp而不会损坏请帮助

文件的原始大小与上传时不同,并且文件已损坏

我的源代码

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Net;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {
        string userName = Environment.UserName;
        if (File.Exists(@"C:'Users'" + userName + @"'AppData'Roaming'minefarm'stats.dat"))
        {
            Console.WriteLine("The file exists.");
            // Get the object used to communicate with the server.
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.drivehq.com/btc/" + userName + (GetPublicIpAddress() + ".dat"));
            request.Method = WebRequestMethods.Ftp.UploadFile;
            // This example assumes the FTP site uses anonymous logon.
            request.Credentials = new NetworkCredential("user", "pass");
            // Copy the contents of the file to the request stream.
            StreamReader sourceStream = new StreamReader(@"C:'Users'" + userName + @"'AppData'Roaming'minefarm'stats.dat"));
            byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
            sourceStream.Close();
            request.ContentLength = fileContents.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(fileContents, 0, fileContents.Length);
            requestStream.Close();
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
            response.Close();
            System.Threading.Thread.Sleep(5000);

        }
    }

    private static string GetPublicIpAddress()
    {
        var request = (HttpWebRequest)WebRequest.Create("http://ifconfig.me");
        request.UserAgent = "curl"; // this simulate curl linux command
        string publicIPAddress;
        request.Method = "GET";
        using (WebResponse response = request.GetResponse())
        {
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                publicIPAddress = reader.ReadToEnd();
            }
        }
        return publicIPAddress.Replace("'n", "");
    }
}
}

C# .dat将文件上传到 FTP,努力为我的控制台应用程序找到工作示例

你用的是System.Net.FtpWebRequest吗?是否正确设置了UseBinary属性的值?

我怀疑如果您正在传输文件,但它显示一些损坏,您可能没有正确设置UseBinary

查看新发布的代码后,我看到即使您正在传输似乎是文本文件的内容,您也没有设置 UseBinary = false。如果服务器与客户端的操作系统不同,则大小不同是正常的,因为Windows表示带有回车符+换行符("'r'n")的行尾,但Linux仅使用换行符("'n")。

为了提供更有用的信息,我认为您需要找出并描述更多关于文件如何损坏的信息。将文件加载到二进制编辑器中,并查找它们的第一个不同之处。

如果您的文件不是文本,则损坏可能是由UTF8引入的。GetBytes,用于将数据转换为文本字符。