473,698 Members | 2,450 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Deleting files after reading

I wish to delete some files from a directory after reading them but
have the problem that the system says that the files are in use and
cannot delete them even though I have set the StreamReader to null:

DirectoryInfo di = new DirectoryInfo(@ "C:\test\") ;

FileInfo[] fiArray = di.GetFiles("*. txt");

foreach (FileInfo fi in fiArray)
{
Console.WriteLi ne (fi.Name);

StreamReader sr = new StreamReader(fi .FullName);
sr = System.IO.File. OpenText(fi.Ful lName);

sr.Close();
sr = null;

fi.Delete();
}
Am I missing something??

Mar 8 '06 #1
6 9562
Hello be**********@gm ail.com,

GC just doen't collect info and free resource
Call GC.Collect() before fi.Delete and everything will work fine
I wish to delete some files from a directory after reading them but
have the problem that the system says that the files are in use and
cannot delete them even though I have set the StreamReader to null:

DirectoryInfo di = new DirectoryInfo(@ "C:\test\") ;

FileInfo[] fiArray = di.GetFiles("*. txt");

foreach (FileInfo fi in fiArray)
{
Console.WriteLi ne (fi.Name);
StreamReader sr = new StreamReader(fi .FullName);
sr = System.IO.File. OpenText(fi.Ful lName);
sr.Close();
sr = null;
fi.Delete();
}
Am I missing something??

---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche
Mar 8 '06 #2

"Michael Nemtsev" <ne*****@msn.co m> wrote in message
news:9c******** *************** ***@msnews.micr osoft.com...
Hello be**********@gm ail.com,

GC just doen't collect info and free resource
Call GC.Collect() before fi.Delete and everything will work fine
Invoking the GC is almost never the right solution.
If the the StreamReader is not closing the underlying file resource right
away on the Close(), it probably should be.
(There's also a chance the filesystem could also need a small delay between
the Close and the Delete.)
Also, in this code, if OpenText has any problems, the delete won't ever get
called.
I'd try using the IDispose/using pattern. After the using block the stream
should be closed.

foreach (FileInfo fi in fiArray)
{
try
{
Console.WriteLi ne (fi.Name);
using ( StreamReader sr = new StreamReader(fi .FullName))
{
sr = System.IO.File. OpenText(fi.Ful lName);
// ...read the text from sr...
}
}
catch
{
// read problems...
}
// Possibly sleep here for a millisecond or so?? or otherwise twiddle
fi?

try
{
fi.Delete();
}
catch
{
// delete problems...
}
}
I wish to delete some files from a directory after reading them but
have the problem that the system says that the files are in use and
cannot delete them even though I have set the StreamReader to null:

DirectoryInfo di = new DirectoryInfo(@ "C:\test\") ;

FileInfo[] fiArray = di.GetFiles("*. txt");

foreach (FileInfo fi in fiArray)
{
Console.WriteLi ne (fi.Name);
StreamReader sr = new StreamReader(fi .FullName);
sr = System.IO.File. OpenText(fi.Ful lName);
sr.Close();
sr = null;
fi.Delete();
}
Am I missing something??

---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do
not cease to be insipid." (c) Friedrich Nietzsche

Mar 8 '06 #3
Hi,

You are opening the file twice, StreamReader's constructor returns an open
file , ready to be readed, but you are creating another when you call Open

Do this:
StreamReader sr = new StreamReader(fi .FullName);
sr.Close();
fi.Delete();

I assume you deleted your actions (should be between the declaration and the
closing


--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
Mar 9 '06 #4
Hi,
Invoking the GC is almost never the right solution.
You are right, usually you should let the GC to work as it's intended,
alone.
If the the StreamReader is not closing the underlying file resource right
away on the Close(), it probably should be.
(There's also a chance the filesystem could also need a small delay
between the Close and the Delete.)
Don't think so, Close should return once the API close is performed,
otherwise you may get A LOT of problems
Also, in this code, if OpenText has any problems, the delete won't ever
get called.


The delete is not the problem, the Close is. you can get a open file around
until you either close your program or the instance gets out of scope.

using ( StreamReader sr = new StreamReader(fi .FullName))
{
// ...read the text from sr...
}

should be more than enough for that.

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
Mar 9 '06 #5

"Ignacio Machin ( .NET/ C# MVP )" <ignacio.mach in AT dot.state.fl.us > wrote
in message news:OE******** ******@TK2MSFTN GP09.phx.gbl...
Hi,

You are opening the file twice, StreamReader's constructor returns an open
file , ready to be readed, but you are creating another when you call Open
Yikes, I didn't even pay attention to this obvious redundancy - no more
responding to posts without adequate sleep :)

I can almost see that a compile warning should be created here, something
like:

Warning: New object assigned to "sr" on line 121 but never used before
re-assignment on line 123.

This warning could occur if:
- the variable is not maked volatile
- a new class is created on the heap
- a new struct is created that is larger than the lagest simple
value-type
- a new struct is created (regardless of size) with a "non-trivial" ctor
- the new object is never used

so basically:
- anything that's potentially expensive to create and never gets used
- is likely a programmer error (as in this case)
thanks,
m

Do this:
StreamReader sr = new StreamReader(fi .FullName);
sr.Close();
fi.Delete();

I assume you deleted your actions (should be between the declaration and
the closing


--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

Mar 9 '06 #6
Hello Ignacio Machin ( .NET/ C# MVP )" ignacio.machin AT dot.state.fl.us ,

I understand that GC needn't to be called in this case,
but experimented a bit I've found that nothing else works in my enviroment
except GC.Collect

I've tried the disposal patterns and any other cases, but none helps

What's the most interesing, the EXE built on another PC works fine
I> Hi,
I>
Invoking the GC is almost never the right solution.
I> You are right, usually you should let the GC to work as it's
I> intended, alone.
I> If the the StreamReader is not closing the underlying file resource
right
away on the Close(), it probably should be.
(There's also a chance the filesystem could also need a small delay
between the Close and the Delete.) I> Don't think so, Close should return once the API close is performed,
I> otherwise you may get A LOT of problems
I> Also, in this code, if OpenText has any problems, the delete won't
ever get called.

I> The delete is not the problem, the Close is. you can get a open file
I> around until you either close your program or the instance gets out
I> of scope.
I>
I> using ( StreamReader sr = new StreamReader(fi .FullName))
I> {
I> // ...read the text from sr...
I> }
I> should be more than enough for that.
I>
---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche
Mar 9 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
1657
by: John Aherne | last post by:
Being a bit of a newbie, I hope this question isn't too stupid. I have searched the archives and docs for any reports about files and csv messages and not found anything that mentions the problem I am having. I have happily been using the os.remove and file.close commands with a program that sends data to an ftp site. Now I am using the csv module to read some os files and extract some fields that I use to send messages to someone.
5
1948
by: Nora | last post by:
Hi, I have about 200 xml files which contain one line, that I want to delete. This line is always the last line of the file and it always begins with "<?Pub" Transformations don't work as due to this line the document ist not valid and saxon won't perform the transformation. Has anyone an idea how I can get rid of this last line in all documents without having to open all documents and deleting manually?
5
16777
by: Rosa | last post by:
Hi, I'm trying to clear the TIF on Windows XP programmatically with the below code. This code works fine on any folder but the TIF. For some reason the atEnd() statements always defaults to true and no files are deleted in the folder. The peculiarity of this issue is that the files/subfolders cannot be seen through the windows explorer either. I can only access/delete them through a command shell. Any ideas?
0
1405
by: Hrvoje Vrbanc | last post by:
Hello, this is a problem I came upon while building a site based on MCMS 2002 but it's not strictly MCMS-oriented: I have a page that displays a certain content in presentation mode but when an editor clicks "Switch To Edit Site" in MCMS console on the page, the page displays a different content, an interface that editor use for upload and deleting files on the web server. There are no problems with the upload but there is a problem...
6
4558
by: Martin Bischoff | last post by:
Hi, I'm creating temporary directories in my web app (e.g. ~/data/temp/temp123) to allow users to upload files. When I later delete these directories (from the code behind), the application restarts and all active sessions are terminated. This error is also described in detail here:...
5
7517
by: Joe Delphi | last post by:
Hi Newbie to VB.Net and I have a question I need to open a text file, read each line, and if I find something in the line, delete that line from the text file. Can anyone tell me how to do this. Some of my code is below: Try FileOpen(254, "FormSettings.ini", OpenMode.Input)
14
1678
by: micklee74 | last post by:
hi say i have a text file line1 line2 line3 line4 line5 line6 abc
3
2872
by: Kimera.Kimera | last post by:
I'm trying to write a program in VB.net 2003 that basically deletes all files, folders, sub-folders and sub-sub folders (etc). The program is simply for deleting the Windows/Temp folder contents, removing all the files/folders inside it. The problem i am having is that i can only delete files in the Windows/Temp folder, and i can't delete folders if they contain files, i know that you can't do this.
1
1415
by: manojpolawar2008 | last post by:
Hi , i am using asp.net2.0 in that DirectoryInfo object for reading the files. i have added each file record to DataTable object. and bind that to gridview and added one templete field for delete. while deleting the image irs showing an error...... this is used by another process.......so i am not able to delete that file.... and dont wan to restart the IIS.... i have disposed the datatable...
0
8675
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8604
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8897
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8862
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7729
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4370
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4619
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3050
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2331
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.