.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

When processing files recursively, why the top DirectoryInfo always throw a Exception?

Posted By:      Posted Date: October 10, 2010    Points: 0   Category :.NET Framework


I have quite a simple app, which modify the CreationTime property of all the subfiles and subfolders in a folder, the code is like:

    void Mod(DirectoryInfo dir, DateTime time)
      foreach (DirectoryInfo subDir in dir.GetDirectories())
        Mod(subDir, time);
      foreach (FileInfo fi in dir.GetFiles())
        fi.CreationTime = time;
      dir.CreationTime = time;

I call this method with a folder like: C:\a\b, then all the subfiles and subfolders are correctly modified, but WHY I received an Exception: The process cannot access the file 'C:\a\b' because it is being used by another process.

I changed the folder to: C:\a, then C:\a\b was modified successfully, then I got an Exception:The process cannot access the file 'C:\a' because it is being used by another process.

thanks in advance.

View Complete Post

More Related Resource Links

CLR Inside Out: Unhandled Exception Processing In The CLR


In this installment of CLR Inside Out Gaurav Khanna explains everything you need to know about unhandled exception processing in the .NET Framework.

Gaurav Khanna

MSDN Magazine September 2008

Creating database throw exception!

When running SQL commands, it throws error information. Why is it? My env :    windows server 2003 64bit     sql server 2008 . Command :   CREATE DATABASE [AdventureWorks2009]     ON (NAME = 'AdventureWorks2009_Data', FILENAME = N'E:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\AdventureWorks2009_Data.mdf', SIZE = 170, FILEGROWTH = 8),     FILEGROUP DocumentFileStreamGroup CONTAINS FILESTREAM ( NAME = FileStreamDocuments, FILENAME = N'E:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\Documents')     LOG ON (NAME = 'AdventureWorks2009_Log', FILENAME = N'E:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\AdventureWorks2009_Log.ldf' , SIZE = 2, FILEGROWTH = 96); GO     Error information:   Msg 5120, Level 16, State 106, Line 1 Unable to open the physical file "E:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\Documents". perating system error -2147024891: "0x80070005(failed to retrieve text for this error. Reason: 1815)".

Exception during asynchronous processing.


I have a pattern like:

          FunctionDelegatge function = new FunctionDelegatge (MyFunction);

          function.BeginInvoke(arg1, arg2, arg3, new AsyncCallback((far) =>


           if (far.IsCompleted)


            lock (resultLock) result.Add(function.EndInvoke(far));

            Interlocked.Decrement(ref orderCount);


          }), null);

Right now every once and a while I get an exception that simply states 'A severe error occured'. In order to track down this error I was wondering if I could get some help in understanding what happens to an exception during asyncronous processing. Specifically what happens if an exception is raised in 'MyFunction' above? How can I safely catch this exception and still have the exception information available for the asynchronous delegate? Ideally I would like to have status something like the BackgroundWorker class where in the process complete method one can test a property to see if an error occurred. Also what if arg1 etc. was a SqlConnection that if the connection is terminated (this is within a WCF web service)

throw exception message giving internal server error on live site


using vb.net/asp.net 2005

when a user enters a bad email I am doing a check on this and throwing an exception message as follows, this works fine on the test site but for some reason the same code on the live site gives a "internal server error" (http code 500).  The code below:

            If isThisEmailValid(strEmailThatTheUserEntered) Then
		'do something


                Throw New Exception("You entered a bad email address.")

            End If

not certain why this is happening, I assume that it's some server or config difference between the test and live sites.  has anyone seen this before?  For a quick fix i'm registering javascript alert and showing the same text so it works but I would like to figure out why the code above is not working.

as always, thanks for your feedback


JDBC - How can I get it to not throw an exception on ResultSet.isLast()?


Is there some way to configure the Sql Server JDBC driver, or parameters on the Connection or prepareStatement() so that ResultSet.isLast() can be called when I call a stored procedure that returns a ResultSet?

thanks - dave

Very funny video - What's your Metaphor?

throw and catch exception handling



iam inserting record in three tables in a database, iam using begin trans , commit transaction and rollback,

i want to use throw method, if  any value insert wrong, pls correct me, i want to throw the error and

its go to rollback

running = false;
                        int updaterec = DBmgr.ExecuteNonQuery(CommandType.Text, "update ASArrivedcontainer set billgen ='Y' where billgen ='y' and acontinerid in ("+SelValues+")");
                        if (updaterec > 0)
                            running = true;
                            DataSet BillContainerDetails = BillingDetails();

SystemNetworkInterface.GetAdaptersAddresses throw exception



I got this exception:

Exception: System.Net.NetworkInformation.NetworkInformationException
Message: The handle is invalid

when the function SystemNetworkInterface.GetAdaptersAddresses is call the first time.

Call stack:

Source: System
   at System.Net.NetworkInformation.SystemNetworkInterface.GetAdaptersAddresses(AddressFamily family, FixedInfo fixedInfo)
   at System.Net.NetworkInformation.SystemNetworkInterface.PostWin2KGetNetworkInterfaces(AddressFamily family)
   at System.Net.NetworkInformation.SystemNetworkInterface.GetNetworkInterfaces(AddressFamily family)
   at System.Net.NetworkInformation.SystemNetworkInterface.InternalGetIsNetworkAvailable()
   at System.Net.NetworkInformation.NetworkChange.AvailabilityChangeListener.ChangedAddress(Object sender, EventArgs eventArgs)
   at System.Net.NetworkInformation.NetworkChange.AddressChangeListener.AddressChangedCallback(Object stateObject, Boolean signaled)
   at System.Threading._ThreadPoolWaitOrTimerCallback.PerformWaitOrTimerCallback(Object state, Boolean timedOut)

I'm using c# 3.5. The problem occurs on Windows 2008. Not on windows XP.

The network card is: Intel PRO 1000 MT Quad Port NIC.

How could I know the reason why the

lengthy processing (getting data in to 3 different temp files)



I need to do lengthy processing (getting data in to 3 different temp files) for final report.

I have SQL script ready and it works on SQL Studio however, same query from ASP get timeout error.

I am looking for some ideas on how to handle and make this work. Where can I place this processing?



EntityDataSource throw Exception when Update with Self-Reference


For a Table A defined in the DB like this:

A : { id, selfId, name, ... }

where selfId is a foreign key refered to Table A itself.

I generated the Entity automatically like this:

A : { string id; A self; string name, ... }

when i update the entity in gridview Edit/Update CommandField

i got the exception:

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be

Can a timer be used to throw a timeout exception in a WCF operation?


I am developing a webservice for a third party to talk with and they have a requirement of the process running at max 15 seconds.  If the webservice is taking longer than that, then a specific XML reply must be sent back to them to notify that the service is taking too long.

I have tried to do this by encapsulating the 'meat' of the operation in a Try/Catch statement.  Inside the Try portion I create a private scoped System.Timers.Timer with an interval of 15000.  I have a Catch statement that is looking for a TimeoutException which will create the appropriate file when the exception occurs.  There is also an ending Catch statement that just catches any exception and creates another file in that instance.

After I create the timer, I have tried setting Enable to True, setting Enable to True + calling the Start method, and calling the Start method.   After the timer creation/enabling, I am calling a System.Threading.Thread.Sleep(20000).  I have a private shared delegate Sub that is fired when the Timer.OnElapsed event fires.  This Sub has a simple Throw TimeoutException('Timeout Exception Occured!') call in it.

I have tested this each way and none of them seem to actually fire the event on the timer.  The thread sleeps for 20 seconds and then continues on and the service continues on without issue as

An error occured during local report processing. Exception of type 'System.OutOfMemoryException' W


I've been getting this error, randomly when previewing two reports.

It does not seem to be based on report complexity, size, subreports etc. When
reports are deployed to server, they all run fine. I just get the out of memory error locally.

1. I have one version with 2 datasets, and a number of matrix, table and list data regions.
2. I have a second version with only one table data region.
3. There is no custom code, variables, prompts or generally anything other than basic
formatting in the report.
4. Both reports are based on the same SQL table.

I can seem to run the two reports (both based on same SQL table) a few times, and
then they start giving the out of memory error.

I can open other other reports and they preview fine locally.

What I've tried so far to no avail:

1. Deleted the downloaded data before refreshing the two reports.
2. Tried building the two reports before running.
3. Tried changing the process priority to high for devenv.exe.
4. Removed filters in the reports.
5. Changed the physical order of the underlying table.
6. Closed the reports and then re-opened them.
7. Close Visual Studio and Re-Open. This seems to work for a while and then the two
reports start giving the error messages again.
8. Cop

Infopath System.OutOfMemory Exception when try to upload larger files


I am getting “System.outOfMemory” exception when we are trying to upload 40 MB file into InfoPath Browser Form. I have already tried following methods but of no use. Any recommendation to fix the issue??


1.       Have increased upload limits for Web Application level

2.       Have increased Connection time out in IIS


Clean Web.Config Files (VS 2010 and .NET 4.0 Series)

.NET 4 includes a new version of the CLR, and a new .NET 4 specific machine.config file (which is installed side-by-side with the one used by .NET 2, .NET 3 and .NET 3.5).

The new .NET 4 machine.config file now automatically registers all of the ASP.NET tag sections, handlers and modules that we've added over the years, including the functionality for:

.ASP.NET Dynamic Data
.ASP.NET Routing (which can now be used for both ASP.NET WebForms and ASP.NET MVC)
.ASP.NET Chart Control (which now ships built-into ASP.NET V4)
What this means is that when you create a new "Empty ASP.NET application" project in VS 2010, you'll find that the new default application-level web.config file is now clean and simple:


Every self-respected programmer should include exception handling techniques. Sometimes your application will generate an error. Regardless of who was responsible for this error, the programmer or the user, it is up to the first to include the necessary exception handling techniques to keep his/her program from crashing. The .Net environment provides useful techniques for avoiding disastrous errors such as try-catch statements and user-defined exceptions.

Global Exception Handling with ASP.NET

After your global exception handler has done its work, you'll want to redirect the users of your website to a friendly page that tells them that something has gone wrong, and then provide them with customer support information as well as a link back to your web application's home page.

SQL Server 2005 Try and Catch Exception Handling

I'm pretty excited to see that there is some real error handling for T-SQL code in SQL Server 2005. It's pretty painful to have your wonderfully architected .NET solution tainted by less-than-VBScript error handling for stored procedures in the database. The big difference being the addition of TRY..CATCH blocks. Let's take a look:
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend