Proceed If File Doesn't Exist - c#

I have the following code:
public static void readtext(string pathtoText)
{
if (File.Exists(pathtoText))
{
string[] lines = System.IO.File.ReadAllLines(pathtoText);
// Display the file contents by using a foreach loop.
foreach (string line in lines)
{
clearPath(line);
}
}
else
{
Console.WriteLine("{0} doesn't exist, or isn't a valid text file", pathtoText);
}
}
public static void clearPath(string path)
{
if(Directory.Exists(path))
{
int directoryCount = Directory.GetDirectories(path).Length;
if(directoryCount > 0)
{
Console.WriteLine("{0} has Subdirectories to Remove", path);
DirectoryInfo di = new DirectoryInfo(path);
foreach (DirectoryInfo dir in di.GetDirectories())
{
dir.Delete(true);
}
}
else
{
Console.WriteLine("{0} has no directories to remove", path);
}
int fileCount = Directory.GetFiles(path).Length;
if (fileCount > 0)
{
Console.WriteLine("{0} has files to Remove", path);
System.IO.DirectoryInfo di = new DirectoryInfo(path);
foreach (FileInfo file in di.GetFiles())
{
try
{
file.Delete();
}
catch(System.IO.IOException)
{
Console.WriteLine("Please Close the following File {0}", file.Name);
}
}
}
}
else
{
Console.WriteLine("Path Doesn't Exist {0}", path);
}
}
My function reads directories from a text file and passes it to clearPath which checks if the directory exists, and if so, cleans it. My problem is that, if a directory doesn't exist, it stops the program(it doesn't move to the next directory to check if it exists and clean, the for each loop just stops) .
How do I get it to the next directory even if specific directory doesn't exist?

it is possible that you have empty lines in your file?
you can try something like that:
foreach (string line in lines)
{
if (!String.IsNullOrWhiteSpace(line))
{
clearPath(line.trim());
}
}

Related

Issue trying to count number of file in directories + subdirectories

As the title says I'm trying to count the number of file in a directory and subdirectories.
I tried with a foreach loop like that :
public static int hello(string path)
{
string[] files = Directory.GetFiles(path);
string[] dirs = Directory.GetDirectories(path);
int cpt = 0;
foreach (var file in files)
{
try
{
Console.WriteLine(file);
cpt++;
}
catch { }
}
foreach (var directory in dirs)
{
try
{
hello(directory);
}
catch { }
}
return cpt;
}
And the returned value is always the number of file contained in the first path, the cpt var don't get incremented by the number of files in the others directories and subdirectories.
It's strange since the Console.WriteLine(file) shows all the files path in the console box.
It looks like a small issue but I don't really know how to solve it, I don't want to use SearchOption method but I really want to use cpt and increment it at each file.
SOLVED with the following code :
public static int hello(string path)
{
string[] files = Directory.GetFiles(path);
string[] dirs = Directory.GetDirectories(path);
int cpt = 0;
foreach (var file in files)
{
try
{
Console.WriteLine(file);
cpt++;
}
catch { }
}
foreach (var directory in dirs)
{
try
{
cpt+=hello(directory);
}
catch { }
}
return cpt;
}
Thanks to #steryd !
When you descend down the directories you're not saving the count. cpt is unique for each invocation of hello()

It's search repeatedly in the folder

Files and folders before the set date are deleted codes.
However, there is a problem.
I want to check the file and delete in the root folder and check the file and delete in the subfolder only once
but check the file in the root folder after delete the file in the subfolder.
I do not want to repeatedly check the file that I already confirmed.
public void FolderAndFileDelete(DirectoryInfo directoryInfo, SQLiteConnection connection, HashSet<string> splitedExtension, DateTime setTime)
{
FileInfo[] files = directoryInfo.GetFiles();
DirectoryInfo[] directoryInfos = directoryInfo.GetDirectories();
if (files != null)
{
foreach (var file in files)
{
file.Delete();
}
if (subFolderRemoveCheckBox.Checked == true)
{
foreach (DirectoryInfo subfolder in directoryInfos)
{
if (subfolder.GetFiles().Length == 0)
{
subfolder.Delete();
}
else if (subfolder.GetFiles().Length != 0)
{
this.FolderAndFileDelete(subfolder, connection, splitedExtension, setTime);
}
if (!subfolder.Exists)
return;
}
}
}
}
How can I fix it?
Your method can be reduced to something a little simpler, since you can pass true to the Delete method of a DirectoryInfo if you want it to remove all files and sub-directories. Note that I added a bool parameter to specify if sub-folders should be removed, so you would pass subFolderRemoveCheckBox.Checked for this argument:
public void DeleteContents(DirectoryInfo directoryInfo, bool includeSubFolders = false)
{
foreach (var file in directoryInfo.GetFiles())
{
file.Delete();
}
if (includeSubFolders)
{
foreach (var subDirectory in directoryInfo.GetDirectories())
{
subDirectory.Delete(true);
}
}
}

C# file backup using directory structure

I have a location like: C:\Backups
I have multiple locations such as:
C:\Users\Peter\Books
C:\ProgramData\Library
C:\Tests\Testing\Tester\
How can I copy everything in each of the locations to the backup location, so that If I drop everything in the backup location folder into C: it will overwrite all the files there with the backup? Basically how can I create the entire structure for backup.
So Far:
public void Init()
{
_locationsToBackup = new List<string>();
DataSet dataSet = _settings.Pull();// dataset is set here
DataTable settingsTable = dataSet.Tables[0];
int valueIndex = 0;
foreach (DataColumn coll in settingsTable.Columns)
{
if (coll.ColumnName == "Value")
{
break;
}
valueIndex++;
}
foreach (DataRow row in settingsTable.Rows)
{
int start = 0;
foreach (DataColumn col in settingsTable.Columns)
{
if (col.ColumnName == "SettingType")
{
string settingRowValue = row.ItemArray[start].ToString();
int settingType = Convert.ToInt32(settingRowValue);
if (settingType == 3)
{
String location = row.ItemArray[valueIndex].ToString();
AddNewLocationToBackup(location);
break;
}
}
start++;
}
}
}
public void StartBackup()
{
//make sure backup folder exists in correct location
// if not then create it.
if(!Directory.Exists(#"C:\ProgramData\Test\Backups"))
{
Directory.CreateDirectory(#"C:\ProgramData\Test\Backups");
}
foreach(string currentLocation in LocationsToBackup)
{
if (Directory.Exists(currentLocation))
{
// copy all files from currentLocation and put into backups
CopyFilesToDirWithSamePath(currentLocation, #"C:\ProgramData\Test\Backups" + #"\" + currentLocation);
}
}
}
}
public void CopyFilesToDirWithSamePath(string sourceDirInput, string targetDirInput)
{
string sourceDir = sourceDirInput;
string targetDir = targetDirInput;
foreach (var file in Directory.GetFiles(sourceDir))
{
File.Copy(file, System.IO.Path.Combine(targetDir, System.IO.Path.GetFileName(file)), true);
}
}
//Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(SourcePath, "*",
SearchOption.AllDirectories))
Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath));
//Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.GetFiles(SourcePath, "*.*",
SearchOption.AllDirectories))
File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath), true);
I hope this will help you
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
I use FileSelectionManager library, take a look to this example:
http://www.fileselectionmanager.com/#Copying%20and%20moving%20files
Hope it hepls.

Delete all files from a directory except for folder and it's contents

I am trying to remove all files on my storage card without removing one. I can keep the directory I specify but not its contents with my current code. It just leaves the blank
folder data because it removes everything inside. How can I keep it from removing that folder and its contents?
private void button1_Click(object sender, EventArgs e)
{
ScanDirectory scanDirectory = new ScanDirectory();
scanDirectory.WalkDirectory(#"/Storage Card");
scanDirectory.WalkDirectory(#"/Application");
}
public class ScanDirectory
{
public void WalkDirectory(string directory)
{
WalkDirectory(new DirectoryInfo(directory));
}
private static void WalkDirectory(DirectoryInfo directory)
{
// Scan all files in the current path
foreach (FileInfo file in directory.GetFiles())
{
file.Attributes &= ~FileAttributes.ReadOnly;
var name = file.Name;
name = name.ToLower();
if (name != "test.txt")
{
file.Delete();
}
}
DirectoryInfo[] subDirectories = directory.GetDirectories();
foreach (DirectoryInfo subDirectory in subDirectories)
{
WalkDirectory(subDirectory);
subDirectory.Attributes &= ~FileAttributes.ReadOnly;
var name = subDirectory.Name;
name = name.ToLower();
if (name != "data")
{
subDirectory.Delete();
}
}
}
}
The problem is the way in which the recursive function calls are done: the main function private static void WalkDirectory(DirectoryInfo directory) deletes all files and is called every time (even while analysing a subdirectory). Here you have a fix to make this code work as you wish:
private static void WalkDirectory(DirectoryInfo directory)
{
if (directory.Name.ToLower() != "data")
{
// Scan all files in the current path
foreach (FileInfo file in directory.GetFiles())
{
file.Attributes &= ~FileAttributes.ReadOnly;
var name = file.Name;
name = name.ToLower();
if (name != "test.txt")
{
file.Delete();
}
}
DirectoryInfo[] subDirectories = directory.GetDirectories();
foreach (DirectoryInfo subDirectory in subDirectories)
{
WalkDirectory(subDirectory);
subDirectory.Attributes &= ~FileAttributes.ReadOnly;
var name = subDirectory.Name;
name = name.ToLower();
if (name != "data")
{
subDirectory.Delete();
}
}
}
}
private static void WalkDirectory(DirectoryInfo directory)
{
if (directory.Name.ToLower() != "data")
{
// Scan all files in the current path
foreach (FileInfo file in directory.GetFiles())
{
file.Attributes &= ~FileAttributes.ReadOnly;
var name = file.Name;
name = name.ToLower();
if (name != "test.txt")
{
file.Delete();
}
}
DirectoryInfo[] subDirectories = directory.GetDirectories();
foreach (DirectoryInfo subDirectory in subDirectories)
{
WalkDirectory(subDirectory);
subDirectory.Attributes &= ~FileAttributes.ReadOnly;
var name = subDirectory.Name;
name = name.ToLower();
if (name != "data")
{
subDirectory.Delete();
}
}
}
}

Error In search in Root Drive like D:\

I write this code and work when I select any folder (with search option = SearchOption.AllDirectories ) but for
Drive Like D:\ I get error
" access to path D:\System Volume Information is denied"
and I add "\" to this path but still get error
if (dirListBox.Items.Count == 0)
{
foreach (int Index in disksListBox.CheckedIndices)
{
String Dir = disksListBox.Items[Index].ToString().Substring(0, 2);
Dir += #"\";
if (CheckExists(Dir))
{
Dirs.Add(Dir);
}
}
}
else
{
for (int Index = 0; Index < dirListBox.Items.Count; Index++)
{
String Dir = dirListBox.Items[Index].ToString();
Dirs.Add(Dir);
}
}
if (rdb_thisdir.Checked == true)
OptionDir = SearchOption.TopDirectoryOnly;
else
OptionDir = SearchOption.AllDirectories; // when search D:\ , Get Error But Work for Folder
if (rdbversion1.Checked == true)
{
ListViewItem lstitm = new ListViewItem();
foreach (String Dir in Dirs)
{
try
{
DirectoryInfo DirInfo = new DirectoryInfo(Dir);
FileInfo[] FileS = DirInfo.GetFiles(SearchPattern,OptionDir); //error when Dir="D:\\"
foreach (FileInfo file in FileS)
{
try
{
if (Check_Attributes(file) && Check_DateTime(file))
{
listFileFounded.Items.Add(file.FullName.ToString());
lstitm = lwfound.Items.Add(file.Extension.ToString());
lstitm.SubItems.Add(file.Name.ToString());
lstitm.SubItems.Add((file.Length / 1024).ToString());
lstitm.SubItems.Add(file.Attributes.ToString());
lstitm.SubItems.Add(file.FullName.ToString());
}
}
catch
{ }
}
}
catch ()
{
}
}
Your D: drive contains a folder "System Volume Information" that you don't have the privileges to access. So you will need to either not access it, or catch the exception and handle it to your liking. Not having access to a folder is not uncommon outside of ones own PC, so you might want to think about handling that scenario in your user interface. Maybe paint the folder in grey or display a lock icon or something.
There was a trick to do it. Do Enable Sharing to this folder.
For more information id here
Or do this trick .....
static void RecursiveGetFiles(string path)
{
DirectoryInfo dir = new DirectoryInfo(path);
try
{
foreach (FileInfo file in dir.GetFiles())
{
MessageBox.Show(file.FullName);
}
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("Access denied to folder: " + path);
}
foreach (DirectoryInfo lowerDir in dir.GetDirectories())
{
try
{
RecursiveGetFiles(lowerDir.FullName);
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Access denied to folder: " + path);
}
}
}
}
kamil Krasinsky answered it .. here

Categories