串口readline方法读取奇怪的字符

时间:2014-11-17 20:44:58

标签: c# serial-port

我正在开发一个项目,用于在两个COM端口之间传输文件。 首先,在将文件转换为字节数组并将其发送到第二个COM之前,我将获取文件名,扩展名和大小。 问题是我在第一个readline方法开头遇到奇怪的字符,我发送文件名,如下所示:

"\0R\0\0\0\0\0\b\0\0\0S\0BAlpha" // file name 
".docx" // file extension
"11360" // file size

这是我用来发送文件的代码:

            Send sfile = new Send();
            string path = System.IO.Path.GetFullPath(op.FileName);
            sfile.Bytes = File.ReadAllBytes(path);
            int size = sfile.Bytes.Length;
            sfile.FileName = System.IO.Path.GetFileNameWithoutExtension(path);
            sfile.Extension = System.IO.Path.GetExtension(path);
            FileStream fs = new FileStream(path,FileMode.Open);
            BinaryReaderbr = new BinaryReader(fs);

            serialPort1.WriteLine(sfile.FileName); // sending file name
            serialPort1.WriteLine(sfile.Extension);// sending extension
            serialPort1.WriteLine(size.ToString());// sending size 


            byte[] b1 = br.ReadBytes((int)fs.Length);
            for (int i = 0; i <= b1.Length; i++)
            {
                serialPort1.Write(b1, 0, b1.Length);
            }

            br.Close();
            fs.Dispose();
            fs.Close();
            serialPort1.Close();

并且以下代码用于接收正在发送的数据:

        string path1 = serialPort1.ReadLine();
        string path2 = serialPort1.ReadLine();
        string path3 =  serialPort1.ReadLine();
        int size = Convert.ToInt32(path3);
        string path0 = @"C:\";
        string fullPath = path0 + path1 + path2;
       // File.Create(fullPath);
        FileStream fs = new FileStream(fullPath, FileMode.Create);
        byte[] b1 = new byte[size];
        for (int i = 0; i < b1.Length; i++)
        {
            serialPort1.Read(b1, 0, b1.Length);
        }
        fs.Write(b1, 0, b1.Length);
        fs.Close();
        serialPort1.Close();

1 个答案:

答案 0 :(得分:1)

您没有正确写入字节。它应该是:

    byte[] b1 = br.ReadBytes((int)fs.Length);
    serialPort1.Write(b1, 0, b1.Length);

你阅读它们的方式也是完全错误的。它应该是:

    byte[] b1 = new byte[size];
    for (int i = 0; i < b1.Length; )
    {
        i += serialPort1.Read(b1, i, b1.Length - i);
    }