无法将输出写入文本文件

时间:2013-12-15 22:58:29

标签: c# io

请建议使用以下代码将错误写入文本文件。正在创建该文件但未写入任何内容。虽然程序运行正常,但没有任何异常,但在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);

    }
}

1 个答案:

答案 0 :(得分: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);
    }
}