我的using语句应该放在哪里?以及在哪里放钓鱼



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

编辑:很抱歉发布了那个代码片段腮红那很糟糕: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);
        }
    } 
}

您不需要多次打开文件-实际上您现在已经打开了三次。这应该没问题;如果该文件已经存在,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 -但是为什么呢?如果写入文件失败,您是否一定要在此方法中"处理"异常,而不是让它冒泡到调用者那里?

首先,我不明白这么多流的用途,但你可以在许多地方使用using:

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

您可以跳过前两个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
)

类型:系统。属性是否追加数据文件。如果文件存在且append为false,则覆盖该文件。如果文件存在并且append为true,则将数据追加到文件。否则创建新文件

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

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

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

现在,您拥有的代码相当于:

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

但是我不知道你为什么打开第一个文件。
关于第二个,我相信您尝试使用以下方法创建文件:
但是也有其他的方法

// 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);
       }
}

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

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

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

相关内容

  • 没有找到相关文章

最新更新