61,817
社区成员




// For Directory.GetFiles and Directory.GetDirectories
// For File.Exists, Directory.Exists
using System;
using System.IO;
using System.Collections;
public class RecursiveFileProcessor
{
public static void Main(string[] args)
{
foreach(string path in args)
{
if(File.Exists(path))
{
// This path is a file
ProcessFile(path);
}
else if(Directory.Exists(path))
{
// This path is a directory
ProcessDirectory(path);
}
else
{
Console.WriteLine("{0} is not a valid file or directory.", path);
}
}
}
// Process all files in the directory passed in, recurse on any directories
// that are found, and process the files they contain.
public static void ProcessDirectory(string targetDirectory)
{
// Process the list of files found in the directory.
string [] fileEntries = Directory.GetFiles(targetDirectory);
foreach(string fileName in fileEntries)
ProcessFile(fileName);
// Recurse into subdirectories of this directory.
string [] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach(string subdirectory in subdirectoryEntries)
ProcessDirectory(subdirectory);
}
// Insert logic for processing found files here.
public static void ProcessFile(string path)
{
Console.WriteLine("Processed file '{0}'.", path);
}
}
using System;
using System.IO;
class Test
{
public static void Main()
{
// Specify the directories you want to manipulate.
string path = @"c:\MyDir";
string target = @"c:\TestDir";
try
{
// Determine whether the directory exists.
if (!Directory.Exists(path))
{
// Create the directory it does not exist.
Directory.CreateDirectory(path);
}
if (Directory.Exists(target))
{
// Delete the target to ensure it is not there.
Directory.Delete(target, true);
}
// Move the directory.
Directory.Move(path, target);
// Create a file in the directory.
File.CreateText(target + @"\myfile.txt");
// Count the files in the target directory.
Console.WriteLine("The number of files in {0} is {1}",
target, Directory.GetFiles(target).Length);
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
finally {}
}
}