2011-12-20 2 views
2

다음 Console.Write 방법은 완벽하게 작동, 및 텍스트 출력이 화면에 표시되어 있지만내가 텍스트 파일에 텍스트를 쓰기를 시도하고

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

     } 

하지만, TextWriter 메서드를 사용하면 응용 프로그램이 100 개의 오류를 생성하고 (계속) 지정된 출력 파일에 아무 것도 출력하지 않습니다.

"Console.Write (Convert.ToChar (b [ 나는]));" 텍스트 파일에? 다음은

가 오류의 예입니다 : 서버가 포트 8111에서 실행

... 지역 종점 입니다 : 172.16.0.37 : 8111가 연결 ..... 연결 대기 중 받아 들인 내용 172.16.0.37:59307 수신 ... // 오류 ..... 에서 System.IO .__ Error.WinIOError (Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init (String path, FileMode 모드, FileAccess 액세스, Int32 권한, 부울 useRights, FileShare 공유, Int32 bufferSize, FileOptions 옵션, SECURITY_ATTRIBUTES secAttrs, St ( 경로, FileMode 모드, FileAccess 액세스, FileShare 공유, Int32 bufferSize, FileOptions 옵션)에서 msg.BufferProxy.BufferFile (String path, 부울 추가)에서 의 Integer.Main()에있는 System.IO.StreamWriter..ctor (문자열 경로)의 System.IO.StreamWriter..ctor (문자열 경로, 부울 추가, 인코딩 인코딩, Int32 버퍼 크기) : \ Users \ Limited \ Desktop \ IntegClient \ IntegServer \ IntegServer \ Program.cs : 38 오류 ..... System.Net.Sockets.Socket.DoBind (끝점 endPointSnapshot, SocketAddress socketAddress)에서 System.Net .Sockets.Socket.Bind (EndPoint localEP)에 있습니다. System.Net.Sockets.TcpListener.Start (Int32 백 로그) 의 Integer.Main()에서 System.Net.Sockets.TcpListener.Start() C : \ Users \ Limited \ Desktop \ IntegClient \ IntegServer \ IntegServer \ Program.cs : 라인 21 오류 ..... 시스템에서 System.Net.Sockets.Socket.Bind에서 System.Net.Sockets.Socket.DoBind (를 EndPoint endPointSnapshot, SocketAddress를 않은 SocketAddress()를 EndPoint localEP)에서. Integers.Main()의 에있는 System.Net.Sockets.TcpListener.Start() C : \ Users \ Limited \ Desktop \ IntegClient \ IntegServer \ IntegServer \ Program.cs의 Net.Sockets.TcpListener.Start (Int32 백 로그) : 줄 21 오류 ..... System.Net.Sockets.Socket.DoBind (끝점 endPointSnapshot, SocketAddress socketAddress) System.Net.Sockets.TcpListener.Start에서 System.Net.Sockets.TcpListener.Start (INT32 잔고)에 System.Net.Sockets.Socket.Bind (localEP를 EndPoint)()에서

전체 코드는 다음과 같습니다.

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(); 
} 
+0

무엇을 오류? (어쩌면 그들 중 일부만을 ...) – David

+0

'TextWriter'를 사용할 때 얻는 오류는 무엇입니까? –

+2

루프에 새 작성자가 있습니까? 그것은 문제를 요구하고있다 – Rob

답변

0

어쩌면 이것은 무엇을하려는 것입니까?

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])); 
    } 
} 
+0

안녕하세요 David, 코드를 사용할 때이 오류가 발생합니다. 오류 'System.IO.FileStream'에 'WriteLine'에 대한 정의가 없습니다. 'System.IO.FileStream'형식의 첫 번째 인수를 허용하는 확장 메서드 'WriteLine'을 찾을 수 없습니다 (사용 지시문이나 어셈블리 참조가 누락 되었습니까?) – Mike

+0

@Mike : 실수입니다. (코드를 자유롭게 넘기는 것에 대한 제 잘못). 대신에'StreamWriter'에 쓰도록 업데이트했습니다. 비록 이것이 여러 가지 조건 하에서 안전하게 파일을 열면 나는 내 머리 꼭대기를 기억하지 못한다. 파일이 존재하고 쓰기가 가능한지 확인하기 위해 유효성 검사를 수행 할 수 있습니다. – David

+0

텍스트 파일이 매우 (strangley) (strangley) 다음과 같이 보입니다. http://i44.tinypic.com/30s83so.jpg – Mike

0

당신의 문제는 액세스 모드에있는 것처럼 보입니다. 코드를 변경하여 파일 스트림을 액세스 모드/쓰기 또는 다시 쓰기 모드로 전달할 수 있습니까? 여기에 예가 나와 있습니다.

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 
관련 문제