C# 关闭StreamWriter和StreamReader的最佳正确方法

C# 关闭StreamWriter和StreamReader的最佳正确方法,c#,C#,我一直试图组织一个代码,这是一个混乱!第一个也是我目前最大的问题是,我的一个StreamWriter或StreamReader没有打开。使用,我试图组织我的代码。但我的问题是,我不确定应该在哪里关闭它: 我的代码是: public static void ProcessFile(string[] ProcessFile, int id_customer, string directoryinprocess) { StreamWriter Writer = null, Writer2 =

我一直试图组织一个代码,这是一个混乱!第一个也是我目前最大的问题是,我的一个StreamWriter或StreamReader没有打开。使用,我试图组织我的代码。但我的问题是,我不确定应该在哪里关闭它:

我的代码是:

public static void ProcessFile(string[] ProcessFile, int id_customer, string directoryinprocess)
{
    StreamWriter Writer = null, Writer2 = null, Writer3 = null;

    foreach (string filename in ProcessFile)
    {

        // Used for the output name of the file
        var dir = Path.GetDirectoryName(filename);
        var fileName = Path.GetFileNameWithoutExtension(filename);
        var ext = Path.GetExtension(filename);
        var folderbefore = Path.GetFullPath(Path.Combine(dir, @"..\"));
        int rowCount = 0;
        string path_body_out = "";
        string outputname = folderbefore + "output_temp\\" + fileName;

        if (filename.Contains("RO_"))
        {
            Writer = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_hd_intermediate" + ext) { AutoFlush = true };
            Writer2 = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_body_out" + ext) { AutoFlush = true };
            path_body_out = dir + "\\" + "output_temp\\" + fileName + "_hd_intermediate" + ext;
        } // end of if
        else
        {
            Writer3 = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_out" + ext) { AutoFlush = true };
        } // end of else

        using (StreamReader Reader = new StreamReader(@filename))
        {
            while (!Reader.EndOfStream)
            {
                string inputLine = string.Empty;
                inputLine = Reader.ReadLine();

                rowCount++;

                if (filename.Contains("RO_"))
                {
                    if (rowCount <= 4)
                    {
                            Writer.WriteLine(inputLine);
                    }
                    if (rowCount >= 5)
                    {
                        Writer2.WriteLine(inputLine);
                    }
                }
                else
                {
                    { Writer3.WriteLine(inputLine); }
                }

            } // end of the while
        } // end of using Stremreader


        if (path_body_out.Contains("_hd_intermediate"))
        {
            ManipulateHeaderFilesTypeRo(dir, path_body_out);
        }
        else
        { }
    } // end of the foreach


    string[] extensions = { "_fv", "_body", "_out" };

    string[] fileEntriesout = System.IO.Directory.EnumerateFiles(directoryinprocess, "*.csv", System.IO.SearchOption.AllDirectories)
    .Where(file => extensions.Any(ex => Path.GetFileNameWithoutExtension(file).EndsWith(ex)))
        .ToArray();


    foreach (string filenameout in fileEntriesout)
    {
        string destinytablename = null;

        if (filenameout.Contains("_hd_intermediate_fv"))
        { destinytablename = "TBL_DATA_TYPE_RO_HEADER"; }
        else if (filenameout.Contains("_body_out"))
        { destinytablename = "TBL_DATA_TYPE_RO_BODY"; }
        else
        { destinytablename = "TBL_DATA_TYPE_LOAD"; }

        string id_file = Get_id_file(filenameout, id_customer);

        DataTable csvFileData = GetDataTabletFromCSVFile(filenameout, id_file);

        InsertDataIntoSQLServerUsingSQLBulkCopy(csvFileData, destinytablename);

    } // end of the foreach

    //} // end of the foreach

} // end of ProcessFile 
还是在这里

                if (filename.Contains("RO_"))
                {
                    if (rowCount <= 4)
                    {
                            Writer.WriteLine(inputLine);
                    }
                    if (rowCount >= 5)
                    {
                        Writer2.WriteLine(inputLine);
                    }
                }
                else
                {
                    { Writer3.WriteLine(inputLine); }
                }

如果您无法重新组织此代码,以便每个StreamWriter实例都可以包装在using中,那么您可能可以执行以下操作:

StreamWriter Writer = null, Writer2 = null, Writer3 = null;

try
{
    // your existing code
}
catch
{
    // Handle
}
finally
{
    if (Writer != null)
        Writer.Close();
    if (Writer2 != null)
        Writer2.Close();
    if (Writer3 != null)
        Writer3.Close();
}
这确保无论try中发生什么错误,您的编写器都将关闭


在我看来,有条件地实例化对象是一种气味,您应该根据filename.ContainsRO\ux使用不同的实现。您可以使用策略模式,并有不同的文件处理器接口实现,根据文件名选择正确的实现。每个实现只知道如何写入所需的位置。这将允许您在每个writer周围正确使用using。

如果您无法重新组织此代码,以便每个StreamWriter实例都可以包装在using中,那么您可能可以执行以下操作:

StreamWriter Writer = null, Writer2 = null, Writer3 = null;

try
{
    // your existing code
}
catch
{
    // Handle
}
finally
{
    if (Writer != null)
        Writer.Close();
    if (Writer2 != null)
        Writer2.Close();
    if (Writer3 != null)
        Writer3.Close();
}
这确保无论try中发生什么错误,您的编写器都将关闭


在我看来,有条件地实例化对象是一种气味,您应该根据filename.ContainsRO\ux使用不同的实现。您可以使用策略模式,并有不同的文件处理器接口实现,根据文件名选择正确的实现。每个实现只知道如何写入所需的位置。这将允许您在每个书写器周围正确使用using。通常,如果您使用的是一次性对象,我会说使用using块。然而,由于您是有条件地安装一次性对象,我认为使用try-finally块将是您的最佳选择

声明一次性对象并在try块外部将其初始化为null

将一次性对象初始化为try块中所需的实例。创建一次性对象后,请注意不要在try块内的任何位置更改此引用

同样在你的试块内,用一次性物品做所有你需要做的事情

在try块创建finally块之后,catch块是可选的,但是这个方法需要finally块来完成它的工作。在finally块中,检查声明用于保存一次性对象的变量是否为null。如果它们不为null,则关闭它们并使其为null

StreamWriter writer = null;

try {
    if (condA) {
       writer = new StreamWriter("filePath1");
    } else if (condB) {
        writer = new StreamWriter("filePath2");
    } else {
        writer = new StreamWriter("filePath3");
    }

    // do things with writer

} catch (Exception ex) {

} finally {
    if (writer != null) {
        writer.close();
        writer = null;
    }
}

通常,如果你使用一次性物品,我会说使用一个使用块。然而,由于您是有条件地安装一次性对象,我认为使用try-finally块将是您的最佳选择

声明一次性对象并在try块外部将其初始化为null

将一次性对象初始化为try块中所需的实例。创建一次性对象后,请注意不要在try块内的任何位置更改此引用

同样在你的试块内,用一次性物品做所有你需要做的事情

在try块创建finally块之后,catch块是可选的,但是这个方法需要finally块来完成它的工作。在finally块中,检查声明用于保存一次性对象的变量是否为null。如果它们不为null,则关闭它们并使其为null

StreamWriter writer = null;

try {
    if (condA) {
       writer = new StreamWriter("filePath1");
    } else if (condB) {
        writer = new StreamWriter("filePath2");
    } else {
        writer = new StreamWriter("filePath3");
    }

    // do things with writer

} catch (Exception ex) {

} finally {
    if (writer != null) {
        writer.close();
        writer = null;
    }
}

是的,你做对了!现在它正在发挥作用,我将努力改善这一混乱局面,现在我知道这就是问题所在。谢谢。是的,你做对了!现在它正在发挥作用,我将努力改善这一混乱局面,现在我知道这就是问题所在。谢谢。它也适用于此选项!非常感谢。抱歉,但我标记为更正了第一个答案,两个都有效!谢谢。它也适用于此选项!非常感谢。抱歉,但我标记为更正了第一个答案,两个都有效!非常感谢。