gpt4 book ai didi

c# - 我的 using 语句应该放在哪里?在哪里放置try catch?

转载 作者:行者123 更新时间:2023-12-03 21:50:25 25 4
gpt4 key购买 nike

我刚刚开始使用文件流,虽然我使代码可以工作,但我真的很想让它变得漂亮 :) 我不知道在哪里放置 using 语句以便我可以跳过流。关闭(),以及如何使用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 - 但为什么呢?如果写入文件失败,您是否肯定希望在此方法中“处理”异常,而不是让它冒泡给调用者?

关于c# - 我的 using 语句应该放在哪里?在哪里放置try catch?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7753626/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com