我的使用陈述应该在哪里?在哪里放置尝试捕获?

时间:2011-10-13 11:47:13

标签: c# try-catch filestream

我刚开始使用filestream,虽然我让代码工作了,但我真的很想把它做得很好:)我不知道在哪里放置using语句所以我可以跳过stream.Close (),以及如何最终使用try catch。这是我的代码,不是最漂亮的东西,但它有效。双文件流用于清除文件。

编辑:很抱歉发布了非常糟糕的代码段 blush :P我已经发布了第二次尝试:)

internal static void SaveFileAsTxt()
{
    FileStream streamer = new FileStream("Shipping2.txt", FileMode.Append, FileAccess.Write, FileShare.Write);
    streamer.Close();

    FileStream f = File.Open("Shipping2.txt", FileMode.Create);  
    f.Close();

    StreamWriter writer = new StreamWriter("Shipping2.txt", true, Encoding.ASCII);

    foreach (var shipment in _shipments)
    {
        string write = (shipment.Distance + ","+ shipment.Distance).ToString();
        writer.WriteLine(write);

    };

        writer.Close();
}


//--------new code--------


internal static void SaveFileAsTxt()
{
    if (File.Exists("Shipping2.txt"))
    {
        File.Delete("Shipping2.txt");
    }

    using (StreamWriter writer = new StreamWriter("Shipping2.txt", true, Encoding.ASCII))
    { 
        foreach (var shipment in _shipments)
        {
            string write = (shipment.Duration + ","+ shipment.Distance).ToString();
                        writer.WriteLine(write);
        }
    } 
}

6 个答案:

答案 0 :(得分:4)

您不需要多次打开文件 - 而且您实际上正在打开三次次。这应该没事;如果文件已存在,File.CreateText将截断该文件,否则创建它:

// Are you *sure* you want to use ASCII? UTF-8 might be a better bet...
using (TextWriter writer = File.CreateText("Shipping2.txt", Encoding.ASCII))
{
    foreach (var shipment in _shipments)
    {
        // Removed redundant ToString call, and elided local variable.
        // Consider using a format string instead:
        // writer.WriteLine("{0},{1}", shipment.Distance, shipment.Distance);
        writer.WriteLine(shipment.Distance + "," + shipment.Distance);
    }
    // Removed empty statement (trailing semi-colon)
}

现在,你说你想使用try / catch / finally - 但为什么呢?如果你没有写入文件,你肯定想在这个方法中“处理”异常,而不是让它冒泡到调用者那里吗?

答案 1 :(得分:1)

您可以先跳过两个FileStreams,然后只使用StreamWriter,它会为您创建一个文件:

// Single using
using (StreamWriter writer = new StreamWriter(
                                             "Shipping2.txt", 
                                             true, // !!!
                                             Encoding.ASCII))
{
       foreach (var shipment in _shipments)
       {
           string write = (shipment.Distance + "," + shipment.Distance)
                          .ToString();
           writer.WriteLine(write);
       }
}

MSDN:

public StreamWriter(
    string path,
    bool append,
    Encoding encoding
)

<强>追加

  

类型:System.Boolean确定是否要将数据附加到   文件。如果文件存在且append为false,则覆盖该文件。   如果文件存在且append为true,则数据将附加到   文件。 否则,会创建一个新文件

编辑:关于更新的问题(第二部分)

您不需要手动删除文件,只需在StreamWriter的构造函数中指定append = false,它将覆盖文件:

  

如果文件存在且append为false,则覆盖该文件

答案 2 :(得分:1)

首先,我不了解这么多流的用途,但你可以在很多地方使用:

internal static void SaveFileAsTxt()
{
    using(var streamer = new FileStream("Shipping2.txt", FileMode.Append, FileAccess.Write, FileShare.Write))
    {

    }

    using(var f = File.Open("Shipping2.txt", FileMode.Create)) 
    {

    }

    using(var writer = new StreamWriter("Shipping2.txt", true, Encoding.ASCII))
    {
        foreach (var shipment in _shipments)
        {
            string write = (shipment.Distance + ","+ shipment.Distance).ToString();
            writer.WriteLine(write);

        };
    }
}

答案 3 :(得分:0)

现在,您拥有的代码与此相同:

internal static void SaveFileAsTxt() {
    using (FileStream streamer = new FileStream(
         "Shipping2.txt", FileMode.Append, FileAccess.Write, FileShare.Write
    );) {}

    using(FileStream f = File.Open("Shipping2.txt", FileMode.Create)) {}

    using(StreamWriter writer =
        new StreamWriter("Shipping2.txt", true, Encoding.ASCII)) {

        foreach (var shipment in _shipments) {
            string write = (shipment.Distance + "," + shipment.Distance).ToString();
            writer.WriteLine(write);
        }
    }
}

但我不知道你为什么打开第一个档案 关于第二种,我相信你试图用这种方法创建文件,
但也有其他方法可以做到这一点。

答案 4 :(得分:0)

为了与众不同,我将使用LINQ: - )

File.WriteAllLines(
    "Shipping2.txt", 
    _shipments.Select(
        p => string.Format(
            "{0},{1}", 
            shipment.Distance, 
            shipment.Distance)
    ),
    Encoding.ASCII);

此版本需要.NET 4.0。 File.WriteAllLines将创建文件,写入所有行并关闭文件。对于_shipments.Select(p => string.Format("{0},{1}", shipment.Distance, shipment.Distance))的每个元素,_shipments将返回包含shipment.Distance + "," + shipment.Distance的字符串(使用string.Format格式化) `

答案 5 :(得分:0)

// Single using
using (StreamWriter writer = new StreamWriter(
                                             "Shipping2.txt", 
                                             true, // !!!
                                             Encoding.ASCII))
{
       foreach (var shipment in _shipments)
       {
           string write = (shipment.Distance + "," + shipment.Distance)
                          .ToString();
           writer.WriteLine(write);
       }
}