简体   繁体   中英

C# file transfer

I have one question regarding to the way of sending file and receiving file in C# language. I have created a simple file transfer windows form application but it only supports with .txt file format. If I try to send an image file or ms words document file, it could be completely received at the receiving side. 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. 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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