C# load folder names - c#

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.

Related

UnRAR DLL unable to be referenced in C#

I was trying to make a program to clean out some directories on my NAS and I noticed that a lot of folders contained nested rar and zip files and I have plenty of space to unpack them. The program should ask the user for a directory to be cleaned then unpack all rars then delete all of the rars. I'm trying to use UnRAR DLL and I cant even get the rars to unpack. I realize I'm having an issue where visual studio 2022 is refusing to recognize the Unrar DLL in the "using" command. Because of that I've been unable to unpack a single file. This is one my first useful programs so if im missing something basic I understand.
This is my initial attempt:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;
using UnRAR;
namespace Cleaning
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter Directory To Be Cleaned");
string rar_path = Console.ReadLine();
string[] Rars = Directory.GetFiles(rar_path, "*.rar", SearchOption.AllDirectories);
foreach (string rar in Rars)
{
string source = rar;
string dest = "C:\\Users\\Kaleb\\OneDrive\\Desktop\Test Area";
UnRAR unrar = new UnRAR();
unrar.Password = "password_of_myarchive";
unrar.Open(#source, UnRAR.OpenMode.Extract);
while (unrar.ReadHeader())
{
unrar.ExtractToDirectory(#dest);
}
unrar.Close();
}
}
}
}
For reference I have added the UnRAR DLL to the project folder.
SO I was able to get it working with the source code from the great people over at SharpCompress and utilizing their source I've got the following stable build.
using SharpCompress.Archives;
using SharpCompress.Archives.Rar;
using SharpCompress.Common;
using System;
using System.IO;
using System.Linq;
using System.Globalization;
namespace ConsoleApp3
{
public class Program
{
static void Main(string[] args)
{
for (; ; )
{
Console.WriteLine("Enter E to extract all directories in file path");
Console.WriteLine("Enter D to delete all Archives in file path");
Console.WriteLine("REMEMBER TO ALWAYS EXTRACT BEFORE DELETING");
string option = Console.ReadLine();
if (option == "e" || option == "E")
{
Console.WriteLine("Enter Directory To Be Cleaned");
//as a warning this will extract all files from any rar in the slected driectory one at a time in order.
//if a rar is broken it will halt the program until the offendin rar is deleted best way to find is to see what has been extracted so far and go from there
//or one could also limit the directory in order to refine the number of rars to look for
string rar_path = Console.ReadLine();
string[] Rars = Directory.GetFiles(rar_path, "*.rar", SearchOption.AllDirectories);
foreach (string rar in Rars)
{
var DirectoryFinal = Path.GetDirectoryName(rar);
using (var archive = RarArchive.Open(#rar))
{
foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
{
entry.WriteToDirectory(#DirectoryFinal, new ExtractionOptions()
{
ExtractFullPath = true,
Overwrite = true
});
}
};
}
}
else if (option == "d" || option == "D")
{
Console.WriteLine("Enter Directory To Be Cleaned");
//be careful with this i would recomend extracting and then chekcing everything first
string rar_path = Console.ReadLine();
string[] TobeDeleted = Directory.GetFiles(rar_path, "*.r*", SearchOption.AllDirectories);
foreach (string rarstobedeleted in TobeDeleted)
{
File.Delete(rarstobedeleted);
}
}
else
{
Console.WriteLine("Thats not an option try again");
}
Console.WriteLine("Cleaning Complete.");
;
}
}
}
}
This work effectively for rar files only for the time being but will effectively clean up any directories where someone may have downloaded a large amount of files stored in separated rars

How to overwrite all files in a folder with C#?

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");
}

c# Unauthorized exception

Hey guys I got this error I have tried to run program as administrator, no luck still get this error I don't get why it can't clean the shortcuts in the recent documents folder, this is my code:
//this will delete the the files in the Recent Documents directory
private void DeleteRecentDocuments(string RecentDocumentsDirectory)
{
//this is the directory and parameter which we will pass when we call the method
DirectoryInfo cleanRecentDocuments = new DirectoryInfo(RecentDocumentsDirectory);
//try this code
try
{
//loop through the directory we use the getFiles method to collect all files which is stored in recentDocumentsFolder variable
foreach(FileInfo recentDocumentsFolder in cleanRecentDocuments.GetFiles())
{
//we delete all files in that directory
recentDocumentsFolder.Delete();
}
}
//catch any possible error and display a message
catch(Exception)
{
MessageBox.Show("Error could not clean Recent documents directory, please try again");
}
}
I call this method above but dw bout that too much its just calling the method and parameter is the directory. If you want I can post that to.
According to MSDN, FileInfo.Delete() will throw UnauthorizedAccessException when
Source
In order to delete all the files in a directory could do
foreach (string filePath in Directory.GetFiles(recentDocumentsFolder))
{
File.Delete(filePath);
}
If you want to delete the entire directory and any files and subfolders within it you could call
Directory.Delete(recentDocumentsFolder, true);
Your code work for me without any exception, I have select recent document folder using this way and work perfect
System.Environment.GetFolderPath(Environment.SpecialFolder.Recent)
here is my test solution using console application
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string rd = System.Environment.GetFolderPath(Environment.SpecialFolder.Recent);
DeleteRecentDocuments(rd);
Console.ReadLine();
}
//this will delete the the files in the Recent Documents directory
private static void DeleteRecentDocuments(string RecentDocumentsDirectory)
{
//this is the directory and parameter which we will pass when we call the method
DirectoryInfo cleanRecentDocuments = new DirectoryInfo(RecentDocumentsDirectory);
//try this code
try
{
//loop through the directory we use the getFiles method to collect all files which is stored in recentDocumentsFolder variable
foreach (FileInfo recentDocumentsFolder in cleanRecentDocuments.GetFiles())
{
//we delete all files in that directory
recentDocumentsFolder.Delete();
}
}
//catch any possible error and display a message
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Update
some files inside that directory is protected not only for delete but also copy so you can't delete them but most of others can be delete using below code, I have tested
private static void DeleteRecentDocuments(string RecentDocumentsDirectory)
{
//this is the directory and parameter which we will pass when we call the method
DirectoryInfo cleanRecentDocuments = new DirectoryInfo(RecentDocumentsDirectory);
//try this code
try
{
//loop through the directory we use the getFiles method to collect all files which is stored in recentDocumentsFolder variable
foreach (FileInfo recentDocumentsFolder in cleanRecentDocuments.GetFiles())
{
//we delete all files in that directory
File.Delete(RecentDocumentsDirectory + recentDocumentsFolder);
}
}
//catch any possible error and display a message
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Hope this will help you

Recursive looping through files stops abruptly

So I'm trying to run through every file on my harddrive, but it stops once it gets to the 2115th (I think) loop. I believe it is a stack overflow due to my use of recursion, but I'm new to C# and really have no idea. Here's my code, thank you very much.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
namespace test_data
{
class Program
{
static string drive = Path.GetPathRoot(Environment.CurrentDirectory);
static void CrawlDir(string dir)
{
string[] dir_package = {};
List<string> dir_list = new List<string>();
foreach (string scan_dir in Directory.GetDirectories(dir))
{
try
{
dir_list.Add(scan_dir);
}
catch (System.Exception error)
{
Console.WriteLine(error.Message);
}
}
dir_package = dir_list.ToArray();
Process_Package(dir_package);
}
static void Main(string[] args)
{
CrawlDir(drive);
Console.ReadLine();
}
static void Process_Package(string[] package)
{
foreach (string dir in package)
{
Console.WriteLine(dir);
try
{
CrawlDir(dir);
}
catch (Exception)
{
Console.WriteLine("Error!");
}
}
}
}
}
Just use what's built in - Directory.GetDirectories supports an optional parameter to specify if you want to get all directories recursively:
var dirs = Directory.GetDirectories(drive, "*.*", SearchOption.AllDirectories);
Note that this is a blocking call - instead you could use Directory.EnumerateDirectories to receive the directory names one by one as they are being found:
var dirs = Directory.EnumerateDirectories(drive, "*.*", SearchOption.AllDirectories);
foreach(string dir in dirs)
{
Console.WriteLine(dir);
}
Use this overload with SearchOption.AllDirectories so you don't have to do any recursion:
public static string[] GetDirectories(
string path,
string searchPattern,
SearchOption searchOption
)
Recursion looks more or less ok, although you do not really need a list in CrawlDir. If you had a stack overflow you'd get a nasty message.
My guess is - the program completes and stops at ReadLine() waiting for you to press Enter.
You're adding a lot of overhead to each level of recursion by using a List (dir_list), an array (dir_package) and two try/catch loops. I don't know what you're really trying to do, but for this example it's way overkill.
Still, it would take a lot to cause a stack overflow on a modern OS. What error message are you getting?
This code should be equivalent.
using System;
using System.IO;
namespace test_data
{
class Program
{
static string drive = Path.GetPathRoot(Environment.CurrentDirectory);
static void CrawlDir(string dir)
{
foreach (string subDir in Directory.GetDirectories(dir))
{
try
{
Console.WriteLine(subDir);
CrawlDir(subDir);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
static void Main(string[] args)
{
CrawlDir(drive);
Console.ReadLine();
}
}
}

What is the best way to empty a directory?

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);
}
}
}
}
}

Categories

Resources