Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
here so far i know how to delete all files in my dir :

C#
string[] filePaths = Directory.GetFiles(@"c:\Directory\");
foreach (string filePath in filePaths)
File.Delete(filePath);


but how to delete file with extension .txt
so i want to delete all txt files in my dir?
Posted
Comments
ZurdoDev 28-May-13 8:54am    
In your foreach just look at the extension on the filePath.
Gun Gun Febrianza 28-May-13 9:14am    
like this code sir?

string[] dirs = Directory.GetFiles(@"c:\", "*.txt");

There various was,

1) as ryanb31 said, go through the foreach loop and check for the extension and delete if it has it.
2) user the GetFiles overload that accepts a search pattern to filter by *.txt files

http://msdn.microsoft.com/en-us/library/wz42302f(v=vs.90).aspx[^]

Then all you get back from the getfiles method should be the txt tiles.
 
Share this answer
 
Comments
Gun Gun Febrianza 28-May-13 9:14am    
like this code sir?

string[] dirs = Directory.GetFiles(@"c:\", "*.txt");
Pheonyx 28-May-13 9:15am    
That should do the job.
Gun Gun Febrianza 28-May-13 9:20am    
100% work thank you.. :)
Hello,

Change your code as follows
C#
string[] filePaths = Directory.GetFiles(@"c:\Directory\", "*.txt");
foreach (string filePath in filePaths) {
    File.Delete(filePath);
}

More help can be found here on MSDN.

Regards,
 
Share this answer
 
Comments
Gun Gun Febrianza 28-May-13 9:20am    
thankyou sir :)
i got it..
try this
C#
string[] Arr = null;
           Arr = Directory.GetFiles("D:\\Your Directory");
           foreach (string item in Arr)
           {
               if (item.Substring(item.LastIndexOf("."), item.Length - item.LastIndexOf(".")) == ".txt")
               {
                   File.Delete(item);
               }
           }
 
Share this answer
 
v2
Comments
Gun Gun Febrianza 28-May-13 9:20am    
thank you i get new knowledge by learning substring :)
Basmeh Awad 28-May-13 9:24am    
glad to help you..
Welcome:-)
Basmeh Awad 28-May-13 9:24am    
...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900