2013-12-15 84 views
0

請建議將以下代碼寫入文本文件時出現了什麼問題。該文件正在創建,但沒有寫入它。雖然程序運行良好,並沒有異常,但沒有得到任何txt文件。無法將輸出寫入文本文件

class IO 
{ 
    public void write(string name) 
    { 
     try 
     { 
      FileStream fs = new FileStream(@"D:\Infogain\ObjSerial.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite); 
      StreamWriter sw = new StreamWriter(fs); 
      sw.BaseStream.Seek(0, SeekOrigin.Current); 
      sw.Write(name); 
      fs.Close(); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine("Issue in writing: " + ex.Message); 
     } 
    } 

    public static void Main(string[] args) 
    { 
     string name; 
     int ch; 
     List<string> list = new List<string>(); 
     do 
     { 
     Console.WriteLine("Enter name"); 
     name = Console.ReadLine(); 
     IO io = new IO(); 
     io.write(name); 
     Console.WriteLine("Enter 1 to continue"); 
     ch = Convert.ToInt32(Console.ReadLine()); 
     }while(ch==1); 

    } 
} 
+3

請告訴我們什麼錯。 –

回答

1

你應該閱讀一下面向對象編程。在該循環內創建一個新的IO對象是沒有意義的。你的寫功能也有點混亂。

修正版本: (注: 「寫」 功能附加到文件)

public class IO 
{ 
    public static void write(string name) 
    { 
     try 
     { 
      string path = @"e:\mytxtfile.txt"; 
      using (StreamWriter sw = File.AppendText(path)) 
      { 
       sw.WriteLine(name); 
      } 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine("Issue in writing: " + ex.Message); 
     } 
    } 

    public static void Main(string[] args) 
    { 
     string name; 
     int ch; 
     List<string> list = new List<string>(); 
     do 
     { 
      Console.WriteLine("Enter name"); 
      name = Console.ReadLine(); 
      write(name); 
      Console.WriteLine("Enter 1 to continue"); 
      ch = Convert.ToInt32(Console.ReadLine()); 
     } while (ch == 1); 
    } 
}