我的 using 语句应该放在哪里?以及在哪里放置 try catch?

发布于 2024-12-10 02:40:54 字数 1224 浏览 1 评论 0原文

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

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

I've just started using filestream, and although I made the code work,- I would really like to make it pretty as well :) I have no idea where to place the using statements so I can skip the stream.Close(), and how to use try catch finally. here is my code, not the prettiest thing, but it works. The double filestream is used to clear the file.

Edit: sorry for posting that code snippet blush that was pretty bad :P I've posted my second try :)

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

伴梦长久 2024-12-17 02:40:54

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

You don't need to open the file more than once - and you're actually opening it three times at the moment. This should be fine; File.CreateText will truncate the file if it already exists, and create it otherwise:

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

Now, you say you want to use try/catch/finally - but why? If you fail to write to the file, do you definitely want to "handle" the exception in this method, rather than letting it bubble up to the caller?

独木成林 2024-12-17 02:40:54

首先,我不明白这么多流的用途,但您可以在很多地方使用 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);

        };
    }
}

Firstly, I dont understand the use for so many streams but you can use using in a number of places:

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

        };
    }
}
爱已欠费 2024-12-17 02:40:54

您可以跳过前两个 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为假,则文件被覆盖。
如果文件存在并且append为true,则数据被追加到
文件。 否则,将创建一个新文件

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

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

如果文件存在并且append为假,则文件被覆盖

You can skip two first FileStreams and just use StreamWriter, it will create a file for you :

// 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

Type: System.Boolean Determines whether data is to be appended to the
file. If the file exists and append is false, the file is overwritten.
If the file exists and append is true, the data is appended to the
file. Otherwise, a new file is created.

EDIT: Regarding an updated question (second part)

You do not need to delete file manually, just specify append = false in constructor of StreamWriter and it will overwrite a file:

If the file exists and append is false, the file is overwritten

眼眸印温柔 2024-12-17 02:40:54

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

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

但我不知道您为什么打开第一个文件。
关于第二个,我相信您尝试使用此方法创建文件,
但还有其他方法可以做到这一点。

Right now, the code you have is equivalent to this:

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

But I don't know why you opened the first file.
In respect to the second, I believe you tried to create the file using this method,
but there are other ways to do that as well.

眼前雾蒙蒙 2024-12-17 02:40:54
// 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);
       }
}
// 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);
       }
}
廻憶裏菂餘溫 2024-12-17 02:40:54

为了与众不同,我将使用 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)) 将返回/code>,包含 shipment.Distance + "," +shipment.Distance 的字符串(使用 string.Format 格式化)
`

Just to be different, I'll use LINQ :-)

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

This version requires .NET 4.0. File.WriteAllLines will create the file, write all the lines and close the file. _shipments.Select(p => string.Format("{0},{1}", shipment.Distance, shipment.Distance)) will return, for each element of _shipments, a string containing shipment.Distance + "," + shipment.Distance (formatted using string.Format)
`

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文