C#写入多个文件而不必不断关闭/重新打开流.SteamWriter?

Dan*_*ard 5 c# split streamwriter streamwriter.write

我试图从Access数据库中读取一个表,然后将该表中的数据排序为多个文本文件.关键是要写入的文件名取决于每条记录中的值.这是我的第一个C#应用程序,所以你可以认为我是"绿色".我还应该提一下,我正在使用Access数据库,直到我能够得到代码,最终它将从拥有数百万条记录的SQL服务器中提取出来.

我现在有代码工作,但问题是有大量的文件打开/关闭操作.我想只打开一次文件,因为它会将这些文件写入网络驱动器.这本质上是一个在服务器上运行的粘合应用程序 - 所以还有一些其他限制 - 我无法保存到本地驱动器然后复制到网络.我无法在拉动之前对查询进行排序.运行时我无法对服务器资源产生负面影响.

可能最好的方法是使用哈希表.检查文件是否已打开,如果没有,请将其打开并将文件句柄保存在哈希表中.完成后立即关闭它们.但是,我找不到如何同时使用多个StreamWriter对象的示例.

我期望找到相对容易的答案,但我似乎找不到他的解决方案.我怀疑StreamWriter是用于此的错误类.

我能找到的最接近的上一个问题来自CodeProject页面.在那个页面上,他们说保持文件开放的做法很糟糕,应该避免,但页面不解释原因,也不提供示例替代方案.有人建议将整个数据集加载到内存中,然后对其进行操作,但这对我来说不是一个选项,因为表中会有太多数据.

这是我到目前为止所拥有的.

String strConnection;
String strQuery;
String strPunchFileNameTemplate;

// Define our Variables
strConnection = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=ClockData.accdb";
strQuery = @"SELECT * FROM ClockPunches";   
strPunchFileNameTemplate = @"C:\PUNCHES\%READER%.TXT";      

// OleDbConnection implements iDisposable interface, so we must scope out its usage.
// Set up Connection to our data source
using (OleDbConnection ConnObj = new OleDbConnection(strConnection))    {

    // Create a Command with our Query String
    OleDbCommand CmdObj = new OleDbCommand(strQuery,ConnObj);

    // Open our Connection
    ConnObj.Open();

    // OledbDataReader implements iDisposable interface, so we must scope out its usage.
    // Execute our Reader
    using (OleDbDataReader ReaderObj = CmdObj.ExecuteReader(CommandBehavior.KeyInfo))   {

        // Load the source table's schema into memory (a DataTable object)
        DataTable TableObj = ReaderObj.GetSchemaTable();

        // Parse through each record in the Reader Object
        while(ReaderObj.Read()) {

            // Extract PunchTime, CardNumber, and Device to separate variables
            DateTime dtTime = ReaderObj.GetDateTime(ReaderObj.GetOrdinal("PunchTime"));
            Int16 intID = ReaderObj.GetInt16(ReaderObj.GetOrdinal("CardNumber"));
            String strReader = ReaderObj.GetString(ReaderObj.GetOrdinal("Device"));

            // Translate the device name into a designated filename (external function)
            strReader = GetDeviceFileName(strReader);

            // Put our dynamic filename into the path template
            String pathStr = strPunchFileNameTemplate.Replace("%READER%",strReader);

            // Check to see if the file exists.  New files need an import Header
            Boolean FileExistedBool = File.Exists(pathStr);

            // StreamWrite implements iDisposable interface, so we must scope out its usage.
            // Create a Text File for each Device, Append if it exists
            using (StreamWriter outSR = new StreamWriter(pathStr, true))    {

                // Write our Header if required
                if (FileExistedBool == false)   {
                    outSR.WriteLine("EXAMPLE FILE HEADER");
                }

                // Set up our string we wish to write to the file
                String outputStr = dtTime.ToString("MM-dd-yyyy HH:mm:ss") + " " + intID.ToString("000000");

                // Write the String
                outSR.WriteLine(outputStr);

                // End of StreamWriter Scope - should automatically close
            }
        }
        // End of OleDbDataREader Scope - should automatically close
    }
    // End of OleDbConnection Scope - should automatically close
}
Run Code Online (Sandbox Code Playgroud)

Cas*_*rah 2

这是你自己陷入的一个非常有趣的问题。

缓存文件处理程序的问题在于,大量的文件处理程序会耗尽系统资源,从而导致程序和窗口性能不佳。

如果数据库中的设备数量不太多(少于 100 个),我认为缓存句柄是安全的。

或者,您可以缓存一百万条记录,将它们分发到不同的设备并保存一些,然后读取更多记录。

您可以将记录放入字典中,如下所示:

class PunchInfo
{  
    public PunchInfo(DateTime time, int id)
    {
        Id = id;
        Time = time;
    }
    public DateTime Time;
    public int Id;
}

Dictionary<string, List<PunchInfo>> Devices;
int Count = 0;
const int Limit = 1000000;
const int LowerLimit = 90 * Limit / 100;
void SaveRecord(string device, int id, DateTime time)
{
   PunchInfo info = new PunchInfo(time, id);
   List<PunchInfo> list;
   if (!Devices.TryGetValue(device, out list))
   {
      list = new List<PunchInfo>();
      Devices.Add(device, list);
   }
   list.Add(info);
   Count++;
   if (Count >= Limit)
   {
       List<string> writeDevices = new List<string>();
       foreach(KeyValuePair<string, List<PunchInfo>> item in Devices)
       {
           writeDevices.Add(item.Key);
           Count -= item.Value.Count;
           if (Count < LowerLimit) break;
       }

       foreach(string device in writeDevices)
       {
          List<PunchInfo> list = Devices[device];
          Devices.Remove(device);
          SaveDevices(device, list);
       }
    }
}

void SaveAllDevices()
{
    foreach(KeyValuePair<string, List<PunchInfo>> item in Devices)
        SaveDevices(item.Key, item.Value);
    Devices.Clear();
}
Run Code Online (Sandbox Code Playgroud)

这样您就可以避免打开和关闭文件并拥有大量打开的文件。

100 万条记录占用 20 MB 内存,您可以轻松地将其增加到 1000 万条记录,不会出现任何问题。