Lets say a have some path:
C:\Temp\TestFolder1\TestFolder2
And I have some template:
C:\Temp
So I want to write function that will delete all subdirectories by template
void DeleteSubdirectories(string tlt, string path) {}
If I call this function with given parameters
DeleteSubdirectories("C:\Temp", "C:\Temp\TestFolder1\TestFolder2");
It must delete TestFolder1\TestFolder2 subdirectories from 'C:\Temp
What is the best way to write this function?
If you desire to delecte "C:\Temp" too, use this:
System.IO.Directory.Delete(#"C:\Temp", true);
If you just want to delete the sub directories use this:
foreach (var subDir in new DirectoryInfo(#"C:\Temp").GetDirectories()) {
subDir.Delete(true);
}
System.IO.Directory.Delete("Path", true);
Just use Directory.Delete - the overload I linked has a boolean value that indicates if subdirectories should also be deleted.
What you're describing sounds wierd, but try this:
using System;
using System.IO;
static void DeleteSubDirectories(string rootDir, string childPath)
{
string fullPath = Path.Combine(rootDir, childPath);
Directory.Delete(fullPath);
string nextPath = Path.GetDirectoryName(fullPath);
while (nextPath != rootDir)
{
Directory.Delete(nextPath);
nextPath = Path.GetDirectoryName(nextPath);
}
}
Use it like:
DeleteSubdirectories("C:\Temp", "TestFolder1\TestFolder2");
Obviously, you'll have to implement the exception handling.
Related
I want to make a program in C# that replaces the text of all files in a folder.
I tried this:
using System;
using System.IO;
namespace Stackoverflow
{
class Program
{
static void Main(string[] args)
{
String[] files = Directory.GetFiles(#"C:\Users\test\folder", "*", SearchOption.AllDirectories);
File.WriteAllText(files, "Test");
}
}
}
But I get an error that says that it cannot be converted from "string[]" to "string"
Does anyone know how to solve this?
Instead of
File.WriteAllText(files, "Test");
try using
files.ForEach(file => File.WriteAllText(file, "Test"));
This should work.
EDIT: Or as Heinzi commented, you can similarly solve it in a loop instead of a lambda expression:
foreach (string file in files)
{
File.WriteAllText(file, "Test");
}
I have a large directory of folders and files that contain a space at the end of the name, I'm trying to rename the directories with that space to one without, so that another application would be able to access it.
I'm using C# (but if there's a better option that would fix that issue please suggest) and here's my entire code:
using System;
using System.IO;
using System.Text.RegularExpressions;
namespace removing_spaces_in_directories_names
{
class Program
{
public static string path = "../../../old_directory";
static void Main(string[] args)
{
DirectoryInfo di = new DirectoryInfo(path);
WalkDirectoryTree(di);
Console.ReadLine();
}
static void WalkDirectoryTree(System.IO.DirectoryInfo root)
{
if (root.Name != "old_directory")
{ renameDirectory(root); }
DirectoryInfo[] diArr = root.GetDirectories();
foreach(DirectoryInfo di in diArr)
{
WalkDirectoryTree(di);
}
}
static void renameDirectory(System.IO.DirectoryInfo dir)
{
Console.WriteLine("renaming: " + dir.FullName);
string newName = ReplaceLastOccurrence(dir.FullName, " ", "");
if (Directory.Exists(dir.FullName) == false)
{
//dir.MoveTo(newName);
String oldName = #"\\?\"+dir.FullName;
Directory.Move(oldName,newName);
}
}
public static string ReplaceLastOccurrence(string Source, string Find, string Replace)
{
int place = Source.LastIndexOf(Find);
if (place == -1)
return Source;
string result = Source.Remove(place, Find.Length).Insert(place, Replace);
return result;
}
}
}
I have tried adding "\?\" to the beginning of the folder name as suggested here but that's not working, the error I'd get if I add it is: Illeagal characters in path.
On the other hand if I use dir.MoveTo(newName); without the "\?\" characters I'd get the error: Could not find a part of the path 'Volunteer Information '
How can I go through this if at all? would perhaps running this application on linux rather than windows help?
For each directory that you want to rename (remove the trailing space at the end in this case), let's say your DirectoryInfo variable is called di
You want to do this:
string oldName = di.FullName;
string newName = oldName.TrimEnd();
Directory.Move(oldName, newName);
I rewrote this in a PHP application that's sitting on linux and it worked.
I would like my program to read sub-folders from folder in my solution, but i don't know how to read folder names. I can only find, how to read file names and this is not hard to get to work, but with folders, this doesn't seem to work the same way.
Basically I want to load from "Paevik" (2) sub-folders.
E: I forgot to mention, that I want that list into my comboBox
There is System.IO.Directory.EnumerateDirectories(string Path)-method. It returns a collections with directories. Example:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Program
{
private static void Main(string[] args)
{
try
{
string dirPath = #"\\archives\2009\reports";
List<string> dirs = new List<string>(Directory.EnumerateDirectories(dirPath));
foreach (var dir in dirs)
{
Console.WriteLine("{0}", dir.Substring(dir.LastIndexOf("\\") + 1));
}
Console.WriteLine("{0} directories found.", dirs.Count);
}
catch (UnauthorizedAccessException UAEx)
{
Console.WriteLine(UAEx.Message);
}
catch (PathTooLongException PathEx)
{
Console.WriteLine(PathEx.Message);
}
}
}
See MSDN.
Try DirectoryInfo.EnumerateDirectories Method
http://msdn.microsoft.com/en-us/library/dd413235.aspx
You can use "GetDirectories" to retrieve an array containing full names of all subdirectories.
string[] subdirectories = Directory.GetDirectories("Full path of your parent folder");
See sample on MSDN page.
I am very new to C# and i have written the following class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace PrinterManager
{
class CheckFilesExist
{
public class CheckFilesExist
{
public static bool check(bool isThere)
{
DirectoryInfo di = new DirectoryInfo("c:\temp");
FileInfo[] TXTFiles = di.GetFiles("*.xml");
if (TXTFiles.Length == 0)
{
return isThere;
}
foreach (var fi in TXTFiles)
//return (fi.Exists);
return (fi.Exists);
return check;
}
}
}
}
It should check the directory for *.xml files and add them to an array. If it doesnt find any files then it should return false. It will go through the array and return true or false based on "check".
But i am getting the following error:
Cannot convert method group 'check' to non-delegate type 'bool'. Did
you intend to invoke the method?
It doesnt seem to like, "return check;" at the end.
I basically want to return a check to see if files exists in the folder.
Any ideas why mine isnt working?
Thanks
You can make a one-liner out of your method:
return new DirectoryInfo(#"c:\temp").EnumerateFiles("*.xml").Any();
Note that you are either have to use a literal string (prefixed by #) or properly escape the directory name, i.e. "C:\\temp".
No, it doesn't like return check; at the end - what did you want it to do? Your method is check - so "return true or false based on check" doesn't really make sense. Did you actually mean to return isThere instead?
It's not clear what the parameter is even really meant to be there for, to be honest... and if you've asked a DirectoryInfo for the files in that directory, I'd personally expect them to exist - otherwise why would they be returned?
Oh, and your directory name contains a tab where I suspect you actually want a backslash followed by a t.
I suspect your method would be better as:
public static bool TempDirectoryContainsXmlFiles()
{
DirectoryInfo di = new DirectoryInfo(#"c:\temp");
return di.GetFiles("*.xml").Length > 0;
}
or using LINQ for clarity:
public static bool TempDirectoryContainsXmlFiles()
{
DirectoryInfo di = new DirectoryInfo(#"c:\temp");
return di.GetFiles("*.xml").Any();
}
(You can use EnumerateFiles as shown by BrokenGlass which is more efficient for a large directory, but it's only available in .NET 4 and upwards.)
At a first glance, the problem as to be with the fact of your "check" variable having the same name as your function...
try like this....
private static bool Check_file_Existence(string sFileName)
{
try
{
return File.Exists(sFileName);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
Is there a way to delete all files & sub-directories of a specified directory without iterating over them?
The non elegant solution:
public static void EmptyDirectory(string path)
{
if (Directory.Exists(path))
{
// Delete all files
foreach (var file in Directory.GetFiles(path))
{
File.Delete(file);
}
// Delete all folders
foreach (var directory in Directory.GetDirectories(path))
{
Directory.Delete(directory, true);
}
}
}
How about System.IO.Directory.Delete? It has a recursion option, you're even using it. Reviewing your code it looks like you're trying to do something slightly different -- empty the directory without deleting it, right? Well, you could delete it and re-create it :)
In any case, you (or some method you use) must iterate over all of the files and subdirectories. However, you can iterate over both files and directories at the same time, using GetFileSystemInfos:
foreach(System.IO.FileSystemInfo fsi in
new System.IO.DirectoryInfo(path).GetFileSystemInfos())
{
if (fsi is System.IO.DirectoryInfo)
((System.IO.DirectoryInfo)fsi).Delete(true);
else
fsi.Delete();
}
Why is that not elegant? It's clean, very readable and does the job.
Well, you could always just use Directory.Delete....
http://msdn.microsoft.com/en-us/library/aa328748%28VS.71%29.aspx
Or if you want to get fancy, use WMI to delete the directory.
Here's an extension method based on the OPs original code, which I think is just fine and a bit more readable than other options.
I agree it would be nice to have a single method in the framework to delete the contents of a directory without deleting the directory, but in my opinion, this is the next best thing.
using System;
using System.IO;
namespace YourNamespace
{
public static class DirectoryInfoExtensions
{
public static void EmptyDirectory(this DirectoryInfo di)
{
if (di.Exists)
{
foreach (var file in di.GetFiles())
{
file.Delete();
}
foreach (var directory in di.GetDirectories())
{
directory.Delete(true);
}
}
}
}
}