简体   繁体   English

C#文件传输

[英]C# file transfer

I have one question regarding to the way of sending file and receiving file in C# language. 我对使用C#语言发送和接收文件的方式有一个疑问。 I have created a simple file transfer windows form application but it only supports with .txt file format. 我创建了一个简单的文件传输Windows窗体应用程序,但仅支持.txt文件格式。 If I try to send an image file or ms words document file, it could be completely received at the receiving side. 如果我尝试发送图像文件或ms word文档文件,则可能会在接收方完全接收到它。 But, the received file is unreadable and cannot be opened. 但是,收到的文件不可读,无法打开。 I have done a similar application Java but it works for any file format and I am using the same logic to implement in the C# application. 我已经做了类似的Java应用程序,但是它适用于任何文件格式,并且我使用相同的逻辑在C#应用程序中实现。 Can anyone give me some suggestion or advices on this? 有人可以给我一些建议吗?

SENDING SIDE:
// establish connection
                int port = Convert.ToInt32(txtLocalPort.Text) - 5;
                TcpListener listener = new TcpListener(IPAddress.Parse(txtLocalIP.Text), port);
                listener.Start();

                // get file size
                byte[] data = File.ReadAllBytes(downFile);
                int fSize = data.Length;
                // calculate block numbers, 1024 bytes each block
                int block = fSize / 1024;
                // leftover file bytes, less than 1024 bytes
                int byteLeft = fSize % 1024;

                // convert String to byte
                String cmd = "SEND_FILE" + fSize.ToString();
                buff = new byte[1024];
                buff = Encoding.ASCII.GetBytes(cmd);

                // send message in byte
                msgSocket.Send(buff);

                // accept connection
                TcpClient client = listener.AcceptTcpClient();

                // remote host connected
                if (client.Connected == true)
                {
                    // medium to read file bytes from file chosen
                    BinaryReader readByte = new BinaryReader(File.Open(downFile, FileMode.Open));
                    // medium to send file bytes
                    NetworkStream dataOUT = client.GetStream();

                    // send file bytes based on calculated block numbers
                    for (int i = 0; i < block; i++)
                    {
                        // buffer size
                        buff = new byte[1024];
                        // read file bytes from file chosen
                        readByte.Read(buff, 0, buff.Length);
                        // send file bytes
                        dataOUT.Write(buff, 0, buff.Length);
                        dataOUT.Flush();
                    }

                    // leftover file bytes
                    // buffer size
                    buffLeft = new byte[byteLeft];
                    // read leftover file bytes from file chosen
                    readByte.Read(buffLeft, 0, buffLeft.Length);
                    // send leftover file bytes
                    dataOUT.Write(buff, 0, buffLeft.Length);
                    dataOUT.Flush();

                    MessageBox.Show("File sent successfully.", "File Share", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    // close the medium
                    readByte.Close();
                    dataOUT.Close();
                    client.Close();
                    listener.Stop();

RECEIVING SIDE: 接收端:

// establish connection
        int port = Convert.ToInt32(txtRemotePort.Text) - 5;
        TcpClient client = new TcpClient(Dns.GetHostEntry(IPAddress.Parse(txtRemoteIP.Text)).HostName.ToString(), port);

        // connected to remote host
        if (client.Connected == true)
        {
            // get invalid character
            String invalid = new String(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());

            // remove invalid character
            foreach (char c in invalid)
            {
                fileName = fileName.Replace(c.ToString(), "");
            }

            String downFile = Path.Combine(@"D:\", fileName);

            // file size
            int fSize = fileSize;
            // calculate block numbers, 1024 bytes each block
            int block = fSize / 1024;
            // leftover file bytes, less than 1024 bytes
            int byteLeft = fSize % 1024;

            // medium to receive file bytes
            NetworkStream dataIN = client.GetStream();
            // medium to write file bytes to new file
            BinaryWriter writeByte = new BinaryWriter(File.Open(downFile, FileMode.Create));

            // receive file bytes based on calculated block numbers
            for (int i = 0; i < block; i++)
            {
                // buffer size
                buff = new byte[1024];
                // receive file bytes
                dataIN.Read(buff, 0, buff.Length);
                dataIN.Flush();
                // write file bytes to new file
                writeByte.Write(buff, 0, buff.Length);
                writeByte.Flush();
            }

            // receive leftover file bytes
            // buffer size
            buffLeft = new byte[byteLeft];
            // receive file bytes
            dataIN.Read(buffLeft, 0, buffLeft.Length);
            dataIN.Flush();
            // write file bytes to new file
            writeByte.Write(buffLeft, 0, buffLeft.Length);
            writeByte.Flush();

            MessageBox.Show("File downloaded successfully.", "File Share", MessageBoxButtons.OK, MessageBoxIcon.Information);

            // close the medium
            writeByte.Close();
            dataIN.Close();
            client.Close();

I think I've found out what you did wrong: Instead of 我想我已经发现您做错了什么:
BinaryWriter writeByte = new BinaryWriter(File.Open(downFile, FileMode.Create));

Use BinaryWriter writeByte = new BinaryWriter(File.Open(downFile, FileMode.Append)); 使用BinaryWriter writeByte = new BinaryWriter(File.Open(downFile, FileMode.Append));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM