0

我有代码,我将 xml 文件发送到 ftp 服务器,但 ftp 服务器上的文件大小小于原始文件。我正在尝试启用二进制传输,但结果仍然相同。

FileInfo f = new FileInfo("C:\\Users\\L\\Desktop\\data.xml");
            long original_vel = f.Length; 
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://***");
            request.UseBinary = true;
            request.Method = WebRequestMethods.Ftp.GetFileSize;
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential("*****", "*****");

            StreamReader sourceStream = new StreamReader(@"C:\\Users\\L\\Desktop\\data.xml");
            byte[] fileContents = Encoding.Unicode.GetBytes(sourceStream.ReadToEnd());
            sourceStream.Close();
            request.ContentLength = fileContents.Length;
            long ftp_vel = request.ContentLength;      
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(fileContents, 0, fileContents.Length);
            requestStream.Close();
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            if (original_vel == ftp_vel)
            {
                response.Close();   
            }
            else
            {                
                Odesilani();
            }

原始文件的大小是294 672,但是ftp上的文件有294 670。 The xml file on ftp is valid....But when i compare files in total comander, the original file have: FF FE 3C 00 3F 00.....and the file on ftp have 3C 00 3F 00...但是文件的内容还可以......:/你知道吗?

4

1 回答 1

0

服务器上的 XML 文件是否有效?从您的代码中,您正在使用 Unicode 读取文件。使用 unicode 编码的文件通常有一个位于文件开头的字符,称为字节顺序标记。这可能是您有 2 字节差异的原因,因为它在转换过程中丢失了。

更新任何编码的正确字节顺序标记由Encoding.GetPreamble() 上面代码的修复给出..

        StreamReader sourceStream = new StreamReader(@"C:\\Users\\L\\Desktop\\data.xml");

        //Get Preamble and File Contents
        byte[] bom = Encoding.Unicode.GetPreamble();
        byte[] content = Encoding.Unicode.GetBytes(sourceStream.ReadToEnd());

        //Create Destination array
        byte[] fileContents = new Byte[bom.Length + content.Length];

        //Copy arrays into destination appending bom if available
        Array.Copy(bom, 0, fileContents, 0, bom.Length);
        Array.Copy(content, 0, fileContents, bom.Length, content.Length);


        request.ContentLength = fileContents.Length;
        long ftp_vel = request.ContentLength;
        Stream requestStream = request.GetRequestStream();
        requestStream.Write(fileContents, 0, fileContents.Length);
        requestStream.Close();
        FtpWebResponse response = (FtpWebResponse)request.GetResponse();
        if (original_vel == ftp_vel)
        {
            response.Close();
        }
        else
        {
            Odesilani();
        }

于 2013-08-26T09:48:49.407 回答