C#程序无静态成员却报‘需对象引用访问非静态成员’错误求助
解决C#中“An object reference is required for the non-static field, method, or property 'Encoding.GetBytes(string)'”错误
错误根源
你标注的错误行s.Send(asen.GetBytes(DURL.Text));本身是正确的(通过ASCIIEncoding实例调用GetBytes),实际触发错误的是代码后方的ASCIIEncoding.GetBytes(file)——GetBytes是ASCIIEncoding的实例方法,不能直接用类名调用,必须通过该类的对象实例调用。
解决办法
修正错误调用:
- 方案一:复用已创建的
asen实例:s.Send(asen.GetBytes(file)); - 方案二:使用
Encoding类的静态属性直接获取ASCII编码实例(更简洁):s.Send(Encoding.ASCII.GetBytes(file));
- 方案一:复用已创建的
修正代码中的其他逻辑问题:
- 当前代码发送文件的逻辑错误:
string file = Encoding.UTF8.GetString(bb.AsSpan(0, k));获取的是客户端响应内容,不是读取的文件内容,应发送之前读取的fileContent数组。 - 大文件一次性读取会导致内存溢出,建议分块读取发送。
- 调整逻辑顺序:先确认客户端响应,再读取并发送文件。
- 当前代码发送文件的逻辑错误:
修正后的核心代码片段
void SendFile_Click(object sender, EventArgs e) { try { FileSendProgress.Maximum = 100; IPAddress ipAd = IPAddress.Parse(ClientIP.Text); TcpListener myList = new TcpListener(ipAd, 8001); myList.Start(); MessageBox.Show("The server is running at port 8001..."); MessageBox.Show("The local End point is :" + myList.LocalEndpoint); MessageBox.Show("Looking for other computer"); Socket s = myList.AcceptSocket(); FSStatus.Text = "Connnected to client computer......Sending data now, hold on to your hats. " + FileSendProgress.Value.ToString(); FileSendProgress.Value += 5; // 使用Encoding静态属性简化调用 s.Send(Encoding.ASCII.GetBytes(DURL.Text)); MessageBox.Show("The selected file : " + FileToSend.Text + "is now on it's way to the client computer. It may take a while if a large file is being sent."); // 接收客户端响应 byte[] b = new byte[100]; int k = s.Receive(b); for (int i = 0; i < k; i++) Console.Write(Convert.ToChar(b[i])); FileSendProgress.Value += 45; FSStatus.Text = "Encoding........ " + FileSendProgress.Value.ToString(); // 分块读取发送文件,避免大文件内存溢出 using (System.IO.FileStream fs = new System.IO.FileStream(FileToSend.Text, System.IO.FileMode.Open, System.IO.FileAccess.Read)) using (System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(fs)) { byte[] buffer = new byte[1024]; int bytesRead; FSStatus.Text = "Transmitting now...... " + FileSendProgress.Value.ToString(); FileSendProgress.Value += 15; while ((bytesRead = binaryReader.Read(buffer, 0, buffer.Length)) > 0) { s.Send(buffer, 0, bytesRead); } } FileSendProgress.Value += 35; FSStatus.Text = "File Sent " + FileSendProgress.Value.ToString(); // 清理资源 s.Close(); myList.Stop(); } catch (Exception n) { MessageBox.Show("Please make sure the file is selected, or the file is not supported. " + n); } }
关键说明
- 使用
using语句自动释放文件流和二进制读取器,无需手动调用Close和Dispose。 - 分块读取发送大文件,避免一次性加载整个文件到内存导致溢出。
- 修正了文件发送的逻辑错误,确保发送的是实际读取的文件内容。
内容的提问来源于stack exchange,提问作者Theoneguy
相关产品推荐
相关产品推荐

