【问题标题】:Unable to output text from console to a text file无法将文本从控制台输出到文本文件
【发布时间】:2011-12-20 15:38:04
【问题描述】:

我正在尝试将文本写入文本文件:

        byte[] b = new byte[100];
        int k = s.Receive(b);
        Console.WriteLine("Recieved...");
        for (int i = 0; i < k; i++)
        {
            Console.Write(Convert.ToChar(b[i]));
            //TextWriter tw = new StreamWriter("output.txt");
            //tw.WriteLine(Convert.ToChar(b[i]));

        }

虽然 Console.Write 方法运行良好,并且文本输出显示在屏幕上,但是当我使用 TextWriter 方法时,应用程序会产生 100 个错误(继续)并且不会向指定的输出文件输出任何内容

有没有其他方法可以获得“Console.Write(Convert.ToChar(b[i]));”的输出到文本文件?

以下是错误示例:

服务器在 8111 端口运行...本地端点是 :172.16.0.37:8111 等待连接.....连接已接受 从 172.16.0.37:59307 收到... //错误.....在 System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
在 System.IO.FileStream.Init(String path, FileMode mode, FileAccess 访问、Int32 权限、布尔用户权限、FileShare 共享、Int32 bufferSize,FileOptions 选项,SECURITY_ATTRIBUTES secAttrs,字符串 msgPath, Boolean bFromProxy) 在 System.IO.FileStream..ctor(String 路径、FileMode 模式、FileAccess 访问、FileShare 共享、Int32 bufferSize,FileOptions 选项)在 System.IO.StreamWriter.CreateFile(字符串路径,布尔附加)在 System.IO.StreamWriter..ctor(字符串路径,布尔附加,编码 编码,Int32 bufferSize) 在 System.IO.StreamWriter..ctor(String 路径)在 IntegServer.Main() 中 C:\Users\Limited\Desktop\IntegClient\IntegServer\IntegServer\Program.cs:line 38 错误.....在 System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress) 在 System.Net.Sockets.Socket.Bind(EndPoint localEP) 在 System.Net.Sockets.TcpListener.Start(Int32 backlog) 在 System.Net.Sockets.TcpListener.Start() 在 IntegServer.Main() 中 C:\Users\Limited\Desktop\IntegClient\IntegServer\IntegServer\Program.cs:line 21 错误.....在 System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress) 在 System.Net.Sockets.Socket.Bind(EndPoint localEP) 在 System.Net.Sockets.TcpListener.Start(Int32 backlog) 在 System.Net.Sockets.TcpListener.Start() 在 IntegServer.Main() 中 C:\Users\Limited\Desktop\IntegClient\IntegServer\IntegServer\Program.cs:line 21 错误.....在 System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress) 在 System.Net.Sockets.Socket.Bind(EndPoint localEP) 在 System.Net.Sockets.TcpListener.Start(Int32 backlog) 在 System.Net.Sockets.TcpListener.Start()

完整代码如下:

  try
    {

        IPAddress ipAd = IPAddress.Parse("172.16.0.37"); //use local m/c IP address, and use the same in the client

        /* Initializes the Listener */
        TcpListener myList = new TcpListener(ipAd, 8111);

        /* Start Listeneting at the specified port */
        myList.Start();


            Console.WriteLine("The server is running at port 8111...");
            Console.WriteLine("The local End point is  :" + myList.LocalEndpoint);
            Console.WriteLine("Waiting for a connection.....");


        Socket s = myList.AcceptSocket();
        Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);

        byte[] b = new byte[100];
        int k = s.Receive(b);
        Console.WriteLine("Recieved...");
        using (var txt = File.OpenWrite("output.txt"))
        {
            for (int i = 0; i < k; i++)
            {
                Console.Write(Convert.ToChar(b[i]));
                txt.WriteLine(Convert.ToChar(b[i]));
            }
        }




        ASCIIEncoding asen = new ASCIIEncoding();
        s.Send(asen.GetBytes("The string was recieved by the server."));
        Console.WriteLine("\nSent Acknowledgement to Client");
        /* clean up */
        s.Close();
        myList.Stop();


    }
    catch (Exception e)
    {
        Console.WriteLine("Error..... " + e.StackTrace);
    }
    // Loop the process
    loop();
}

【问题讨论】:

  • 有什么错误? (也许只是其中的一部分......)
  • 使用TextWriter时遇到哪些错误?
  • 你是在循环中创建一个新的作家吗?这是自找麻烦
  • Sergey B 说得对,但他删除了他的答案。他的答案是 add: File.WriteAllBytes("output.txt", b);
  • 仍在查看错误,它似乎也是一个权利问题..

标签: c# .net windows


【解决方案1】:

也许这就是你想要做的?

byte[] b = new byte[100];
int k = s.Receive(b);
Console.WriteLine("Recieved...");
using (var sw = new StreamWriter("output.txt"))
{
    for (int i = 0; i < k; i++)
    {
        Console.Write(Convert.ToChar(b[i]));
        sw.Write(Convert.ToChar(b[i]));
    }
}

【讨论】:

  • 嗨大卫,我在使用您的代码时收到此错误:错误 11 'System.IO.FileStream' 不包含 'WriteLine' 的定义,并且没有扩展方法 'WriteLine' 接受第一个参数可以找到类型“System.IO.FileStream”(您是否缺少 using 指令或程序集引用?)
  • @Mike:哎呀,我错了。 (我的错在于随意编写代码。)我已将其更新为写入StreamWriter。虽然我不记得这是否会在各种条件下安全地打开文件。您可能需要先进行一些验证以查看文件是否存在并且是否可写。
  • 谢谢你,它现在没有崩溃,虽然它在文本文件中非常扼杀(垂直)出现,请参阅:i44.tinypic.com/30s83so.jpg
  • @Mike:这不是您原始代码的意图吗?如果您不希望每个字节都换行,请尝试将.WriteLine 替换为.Write 以获得StreamWriter。检查该对象上的各种重载,看看哪些符合您的需求。
  • 在这种情况下不是,因为它一次写入一个字节,感谢您的回答,我切换到“写入”并且它工作得很好!非常感谢,非常感谢
【解决方案2】:

看起来您的问题出在访问模式中,您可以更改代码以创建文件流,以访问模式/写入或读写模式传递.. 如果您需要关注,这是一个示例

FileStream fsFileStream = null;
fsFileStream = new FileStream("yourOutputFile", FileMode.Open, FileAccess.ReadWrite);
// then add your code here.. also is there a reason why you are declaring such a small byte to write try 512 or 1024 just a suggestion

【讨论】:

    猜你喜欢
    • 2023-03-27
    • 1970-01-01
    • 2020-04-24
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    • 2018-04-18
    • 2011-07-21
    • 2011-01-29
    相关资源
    最近更新 更多