c#使用StreamWriter写入文本文件时出现OutOfMemoryException

本文关键字:OutOfMemoryException 文件 文本 使用 StreamWriter | 更新日期: 2023-09-27 18:17:22

我看过类似这个问题的答案,但我仍然不认为我明白为什么我得到一个异常。

我正试图调试一段代码,这段代码在写入文本文件时抛出"OutOfMemoryException",根据堆栈跟踪。从以下行抛出异常:

WriteToLogFile("Found in EnumerateActiveDirectoryFilteredMembers: " + e.Message);

WriteToLogFile方法如下:

    static void WriteToLogFile(string strLine)
    {
        using (StreamWriter sw = new StreamWriter(strLogFileName, true))
        {
            sw.WriteLine("[" + DateTime.Now.ToString() + "]: " + strLine);
        }
    }

看起来StreamWriter对象有时会抛出这个异常,但是每次调用该方法时,内存不是在该方法结束时重新分配的吗?使用"using"关键字难道不是在确保这个对象被丢弃吗?

抛出异常时,文件只有13 KB——那么这里究竟发生了什么?

更新:OutOfMemoryException不是WriteToLogFile方法这是早些时候扔的,但我不知道这是从哪里来的……我将在catch之前添加try语句的框架:

        try
        {
            if (objSearchResults.Count != 0)
            {
                // ADD TO DATASET HERE //
                string tableName = "tempADhold";
                DataSet domains = new DataSet();
                domains.Tables.Add(tableName);
                //add x number of columns
                domains.Tables[tableName].Columns.Add("DomainID", typeof(string));
                .
                .
                .
                // Get the object from AD.
                foreach (SearchResult objResultUser in objSearchResults)
                {
                    // Init variables and init formatting of strings for adding objects
                    string DomainID = ""; string UserName = ""; string Title = "";
                    .
                    .
                    .
                    objUserEntry = objResultUser.GetDirectoryEntry();
                    // Populate obj and LDAP path variables.  
                    // Perform edits before setting variables. 
                    //   Match strings to SQL Server table sizes.
                    // add objects in same manner:
                    // DomainID
                    if (objUserEntry.Properties["samAccountName"].Count > 0)
                    {
                        DomainID = objUserEntry.Properties["samAccountName"].Value.ToString();
                        if (DomainID.Substring(0, 1).ToUpper() != "N")
                        {
                            WriteToLogFile("RECORD SKIPPED: Invalid N_Number: " + DomainID);
                            continue;  //skip this record
                        }
                        else if (DomainID.Length > 8)
                        {
                            WriteToLogFile("RECORD SKIPPED: Invalid N_Number length. #s ending in 'c' should be skipped: " + DomainID);
                            continue;  //skip this record
                        }
                    }
                    .
                    .
                    .
                    //set up array struct for adding obj
                    ADUserList[0] = DomainID; ADUserList[1] = UserName;
                    ADUserList[2] = ...; ADUserList[3] = ...;
                    ADUserList[4] = ...; ADUserList[5] = ...;
                    ADUserList[6] = ...; ADUserList[7] = ...;
                    ADUserList[8] = ...; ADUserList[9] = ...;
                    ADUserList[10] = ...; ADUserList[11] = ...;
                    ADUserList[12] = ...; ADUserList[13] = ...;
                    ADUserList[14] = ...; ADUserList[15] = ...;
                    ADUserList[16] = ...;
                    if (ADUsersIndex > 0 && ADUsersIndex % 2500 == 0)
                    {
                        //Add to dataset instead of array here...
                        if (InsertRows(domains.Tables[tableName]).Equals(false)) { return false; }
                        domains.Tables[tableName].Rows.Clear();
                    }
                    DataRow myRow = domains.Tables[tableName].NewRow();
                    myRow.ItemArray = ADUserList;
                    domains.Tables[tableName].Rows.Add(myRow);
                    ADUsersIndex++;
                }
                //Write the last rows to the database.
                if (InsertRows(domains.Tables[tableName]).Equals(false)) { return false; }
                objSearchResults.Dispose();

            } //end "if (objSearchResults.Count != 0)"
            else
            {
                WriteToLogFile("Results: No Active Directory filtered members found.");
            }
        }
        catch (Exception e)
        {
           if (e is OutOfMemoryException) throw;
           WriteToConsole("Error in EnumerateActiveDirectoryFilteredMembers: " + e.Message);
           return true;
        }

c#使用StreamWriter写入文本文件时出现OutOfMemoryException

试图运行

WriteToLogFile("Found in EnumerateActiveDirectoryFilteredMembers: " + e.Message);

在错误处理程序中

e几乎肯定已经是一个OutOfMemory异常,但是你的处理程序在试图记录消息时抛出,"隐藏"了真正的堆栈跟踪。

将此添加到WriteToLogFile行之前的错误处理程序中:

if (e is OutOfMemoryException) throw;

这仍然会导致应用程序死亡,但会给出原始错误的真实StackTrace。

相关文章:
  • 没有找到相关文章