2

I am attempting to write text out to a text file:

        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]));

        }

Although the Console.Write method works perfectly, and text output is displayed on screen, but when I use the TextWriter method the application produces 100's of errors (continues) and does not output anything to the output file specified

Is there any other way of getting the output of "Console.Write(Convert.ToChar(b[i]));" to a text file?

Below is a sample of the errors:

The server is running at port 8111... The local End point is :172.16.0.37:8111 Waiting for a connection..... Connection accepted from 172.16.0.37:59307 Recieved... //Error..... at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options) at System.IO.StreamWriter.CreateFile(String path, Boolean append) at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize) at System.IO.StreamWriter..ctor(String path) at IntegServer.Main() in C:\Users\Limited\Desktop\IntegClient\IntegServer\IntegServer\Program.cs:line 38 Error..... at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.Sockets.Socket.Bind(EndPoint localEP) at System.Net.Sockets.TcpListener.Start(Int32 backlog) at System.Net.Sockets.TcpListener.Start() at IntegServer.Main() in C:\Users\Limited\Desktop\IntegClient\IntegServer\IntegServer\Program.cs:line 21 Error..... at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.Sockets.Socket.Bind(EndPoint localEP) at System.Net.Sockets.TcpListener.Start(Int32 backlog) at System.Net.Sockets.TcpListener.Start() at IntegServer.Main() in C:\Users\Limited\Desktop\IntegClient\IntegServer\IntegServer\Program.cs:line 21 Error..... at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.Sockets.Socket.Bind(EndPoint localEP) at System.Net.Sockets.TcpListener.Start(Int32 backlog) at System.Net.Sockets.TcpListener.Start()

The full code follows:

  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();
}
5
  • What are the errors? (Maybe just a subset of them...)
    – David
    Dec 20, 2011 at 15:39
  • What are the errors you get when using the TextWriter? Dec 20, 2011 at 15:40
  • 2
    Are you creating a new writer in the loop?? that's asking for trouble
    – Rob
    Dec 20, 2011 at 15:42
  • Sergey B got it corre,t but he deleted his answer.. His answer was add: File.WriteAllBytes("output.txt", b);
    – Mike
    Dec 20, 2011 at 15:49
  • Still looking at the error it appears to be a rights issue as well..
    – MethodMan
    Dec 20, 2011 at 16:10

2 Answers 2

0

Maybe this is what you're trying to do?

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]));
    }
}
5
  • Hi David, I get this error when using your code: Error 11 'System.IO.FileStream' does not contain a definition for 'WriteLine' and no extension method 'WriteLine' accepting a first argument of type 'System.IO.FileStream' could be found (are you missing a using directive or an assembly reference?)
    – Mike
    Dec 20, 2011 at 15:55
  • @Mike: Oops, my mistake. (My fault for free-handing the code.) I've updated it to write to a StreamWriter instead. Though I can't recall off the top of my head if this will safely open the file under various conditions. You may want to do some validation to see if the file exists and is writable first.
    – David
    Dec 20, 2011 at 16:01
  • thank you it doesnt crash now although it comes out n the text file very strangley (vertically) see this: i44.tinypic.com/30s83so.jpg
    – Mike
    Dec 20, 2011 at 16:04
  • @Mike: Wasn't that the intent of your original code? If you don't want a new line with every byte then try replacing .WriteLine with .Write for the StreamWriter. Check the various overloads on that object to see what fits your needs.
    – David
    Dec 20, 2011 at 16:07
  • not in this case, because it writes one byte at a time, thanks for your answer, I switched to "Write" and it works prefectly! Thank you very much, I appreicate it
    – Mike
    Dec 20, 2011 at 16:12
0

looks like your problem is in the Access Mode can you change your code to create a file Stream passing in the access mode / write or readwrite mode.. here is an example if you need to follow

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.