C# Deleting Directories - c#

I'm working with the .NET Compact Framework 3.5 and want to delete some specific folders and their subfolders. When I run the app it gives IO exception. I've tried to use Directory.Delete(path) method but it didn't work.
How can I solve this problem?
Here is my code :
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Windows.Forms;
namespace Reset_Client
{
static class Program
{
static void Main(){
myfunc();
MessageBox.Show("Cihaz resetlendi!");
}
public static void myfunc()
{
string mainPath = #"\Storage Card\deneme";
try
{
DeleteDirectory(mainPath + "CRM");
DeleteDirectory(mainPath + "BHTS");
DeleteDirectory(mainPath + "IMAGES");
DeleteDirectory(mainPath + "STYLES");
DeleteDirectory(mainPath + "TABLES");
DeleteDirectory(mainPath + "LOG");
File.Delete(mainPath + "Agentry.ini");
File.Delete(mainPath + "Agentry.app");
File.Delete(mainPath + "Agentry.usr");
}
catch (IOException e)
{
myfunc();
}
}
public static void DeleteDirectory(string target_dir)
{
FileInfo fileInfo = new FileInfo(target_dir);
FileAttributes attributes = fileInfo.Attributes;
if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
// set the attributes to nonreadonly
fileInfo.Attributes &= ~FileAttributes.ReadOnly;
}
string[] files = Directory.GetFiles(target_dir);
string[] dirs = Directory.GetDirectories(target_dir);
foreach (string file in files)
{
File.Delete(file);
}
foreach (string dir in dirs)
{
DeleteDirectory(dir);
}
Directory.Delete(target_dir, false);
}
}
}

Why not delete the directory recursively:
Directory.Delete(path, true);
See here.
Also, see here as it may be similar to what you are encountering.

Try this..
var dir = new DirectoryInfo(#FolderPath);
dir.Delete(true);

You are not telling what kind of IO exception you are getting, Are you missing a backslash () in your path?
mainPath + "CRM" becomes "\Storage Card\denemeCRM" and not "\Storage Card\deneme\CRM"

Related

ZipStorer how add directory?

static string mydir = #"C:\Boba\bin\Release\ZipTest";
static string zipfile = string.Concat(mydir, ".zip");
using (ZipStorer zip = ZipStorer.Create(zipfile))
{
zip.AddDirectory(ZipStorer.Compression.Deflate, mydir, zipfile);
}
But after I unpack the archive, folders appear
Dir: Boba -> bin > Release > ZipTest > Files...
How do I add only the ZipTest folder?
I tried to do it like this:
DirectoryInfo d = new DirectoryInfo(mydir);
zip.AddDirectory(ZipStorer.Compression.Deflate, Path.GetFileName(d.FullName), Path.GetFileName(d.FullName), comment);
A Zip archive is created, and inside a folder called ZipTestZipTest, inside there are files and an empty archive called .zip.
How to make it just ZipTest inside the archive?
And so that there is no empty archive in the ZipTest folder?
Try set 3rd argument (_pathnameInZip) for .AddDirectory as empty string:
string dir = #"C:\Boba\bin\Release\ZipTest";
string zipFile = string.Concat(dir, ".zip");
string comment = "My ZipTest";
using (ZipStorer zip = ZipStorer.Create(zipFile))
{
zip.AddDirectory(ZipStorer.Compression.Deflate, dir, string.Empty, comment);
}
If you need without an internal directory, then you can do this:
public static void PackToZipWithoutInternalDir(string dir, string zipout, string comment = "")
{
if (Directory.Exists(dir) && !string.IsNullOrWhiteSpace(dir) && !string.IsNullOrWhiteSpace(zipout))
{
try
{
using var zip = ZipStorer.Create(zipout, comment); // true for stream
zip.EncodeUTF8 = true; // Text encoding
zip.ForceDeflating = true; // Force file compression
foreach (string listDir in Directory.EnumerateDirectories(dir, "*", SearchOption.TopDirectoryOnly))
{
// Add folders with files to the archive
zip.AddDirectory(ZipStorer.Compression.Deflate, listDir, string.Empty);
}
foreach (string listFiles in Directory.EnumerateFiles(dir, "*.*", SearchOption.TopDirectoryOnly))
{
// Add residual files in the current directory to the archive.
zip.AddFile(ZipStorer.Compression.Deflate, listFiles, Path.GetFileName(listFiles));
}
}
catch (Exception ex) { Console.WriteLine(ex); }
}
}
Use:
namespace ZipStorerEx
{
using System;
using System.IO;
public static class Program
{
private static readonly string CurrDir = Environment.CurrentDirectory;
private static readonly string BeginDir = Path.Combine(CurrDir, "YouDir");
private static readonly string ZipOut = $"{BeginDir}.zip";
[STAThread]
public static void Main()
{
Console.Title = "ZipStorerEx";
PackToZipWithoutInternalDir(BeginDir, ZipOut, "It's Good");
Console.ReadKey();
}
}
}

Cannot show the content properly in looping

I have write a c# code to retrieve all the file names follow by printing one of the information inside. Example File contains (file1.mht, file2.mht, file3.mht). Maybe the contain inside is (aaaaaa, bbbbbb, cccccc) follow the sequence of the file.
Example out output:
file1.mht aaaaaa
file2.mht bbbbbb
file3.mht cccccc
But I encounter the problem it cannot loop the file name follow by showing the content inside. Anyone can helps? Current result is it show all the directory first and only done the work for the first one in directory.
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Configuration;
using System.Collections.Specialized;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
DirectoryInfo mht_file = new DirectoryInfo(#"C:\Users\liewm\Desktop\SampleTest\");
FileInfo[] Files = mht_file.GetFiles("*.mht");
string str = "";
string mht_text = "";
string directory = "";
string listInfo = "";
foreach (FileInfo file in Files)
{
str = file.Name;
directory = mht_file + str;
Console.WriteLine(directory);
}
foreach (char filePath in directory)
{
//Here is my work to retrieve the data in the file
Console.WriteLine("Names:" + str + " " + "Component:" + component);
Console.ReadKey();
}
}
}
}
From your question I understand that you want to print the file name followed by the content of the same, if so you can try:
DirectoryInfo mht_file = new DirectoryInfo(#"C:\Users\liewm\Desktop\SampleTest\");
FileInfo[] Files = mht_file.GetFiles("*.mht");
foreach (FileInfo file in Files)
{
// read the content of the file
var content = File.ReadAllText(file.FullName);
// from your question "Example out output: file1.mht aaaaaa"
Console.WriteLine($"{file.Name} {content}");
}
only done the work for the last one in directory.
Yes, that's cause your directory variable is a string string directory = "" which will get overridden by the last value of loop iteration. You rather want to store in a string[] rather if you want to process all of them.
foreach (FileInfo file in Files)
{
str = file.Name;
directory = mht_file + str;
Console.WriteLine(directory);
}
Please try this.
foreach (FileInfo file in Files)
{
str = file.Name;
directory += mht_file + str;
Console.WriteLine(directory);
}

C# Runtime Exception System.TypeInitializationException on some machines

I was trying a very basic script to pull the sizes of all the fires in a directories. Being new to the language, I am aware of the logic but not about the .NET framework. I am currently using .NET Framework 4.5.1 for building this.
Problem:
The tools runs fine meeting all the expectations on my machine and other machines in the lab but I am getting below error message when I am trying to run the script on other machine:
CODE:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Diagnostics;
using System.Threading;
using System.Security.Cryptography;
using System.Numerics;
using System.Text.RegularExpressions;
namespace FolderSize
{
class Program
{
public int foldersize = 0;
public static float foldersizeInMB = float.Parse("0.0");
public static BigInteger SizeInBytes = new BigInteger();
static void Main(string[] args)
{
string directoryName = "";
SizeInBytes = BigInteger.Parse("0");
if (args.GetLength(0)<1)
{
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("No path provided. Please run the command again with correct arguments");
Console.WriteLine("Syntax: ");
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write("FolderSize ");
Console.Write("Path_of_the_folder(InQuotes)");
Console.ForegroundColor = ConsoleColor.White;
}
else
{
directoryName = args[0];
if ( !directoryName.EndsWith(#"\"))
{
directoryName += #"\";
}
DirectoryInfo dir = new DirectoryInfo(directoryName);
if (dir.Exists)
{
getdirNames(dir);
Console.Write((SizeInBytes / (1024 * 1024)).ToString());
}
else
{
Console.Write("Directory Not Found");
}
}
}
private static void getdirNames(DirectoryInfo dir)
{
try
{
foreach (DirectoryInfo d in dir.GetDirectories())
{
foldersizeInMB = float.Parse("0.0");
try
{
foreach (FileInfo f in d.GetFiles())
{
SizeInBytes += f.Length;
string text = f.FullName;
int level = text.Split('\\').Length - 1;
foldersizeInMB += ((float)f.Length/1024);
Console.WriteLine("File?" + level.ToString() + "?" + f.FullName + "?" + ((float)f.Length/1024));
}
Console.WriteLine("Folder?" + (d.FullName.Split('\\').Length-1) + "?" + d.FullName + "?" + foldersizeInMB);
getdirNames(d);
}
catch (Exception)
{
}
}
}
catch
{
}
}
}
}
The problem is in the parsing of floats I guess. The other system you have probably has another decimal separator, most likely because it it set to another language.
This is the failing line:
public static float foldersizeInMB = float.Parse("0.0");
Which should be:
public static float foldersizeInMB = 0.0f;
Or if you need to parse it for some reason, use a culture that supports your format:
public static float foldersizeInMB = float.Parse("0.0", CultureInfo.InvariantCulture);

Split directories using recursion and string.split

Here's my problem. I'm using C# and I'm supposed to design a program that runs a directory and list all of the sub-directories and files within. I've got the basic code down, which is shown below:
namespace DirectorySearch
{
class DirectorySearch
{
const string PATH = #"C:\Directory Search";
static void Main(string[] args)
{
DirSearch(PATH);
}
static void DirSearch(string dir)
{
try
{
foreach (string f in Directory.GetFiles(dir))
Console.WriteLine(f);
foreach (string d in Directory.GetDirectories(dir))
{
Console.WriteLine(d);
DirSearch(d);
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
The problem I'm having is I'm supposed to use stringName.Split('/').Last so the output is all in one straight line, but I have no idea where to place it in the code. The output is supposed to look like:
C:\Directory Search
File1.txt
File2.txt
Folder1
Folder2
File3.txt
Folder3
and so on... I'm pretty sure I can figure out how to make the tabs work after I figure out how to split them up. Any help would be greatly appreciated.
Try this
Console.WriteLine(f.Split('\\').Last());
You just need to use Path.GetFilename which returns directory name (for directories) or file name with extension
foreach (string f in Directory.GetFiles(dir))
Console.WriteLine(Path.GetFileName(f));
foreach (string d in Directory.GetDirectories(dir))
{
Console.WriteLine(Path.GetFileName(d));
DirSearch(d);
}
I'm Not sure if you'r looking for something like this, but you can try this code
namespace DirectorySearch
{
class DirectorySearch
{
const string PATH = #"C:\Directory Search";
static void Main(string[] args)
{
Console.WriteLine(PATH);
DirSearch(PATH);
}
static void DirSearch(string dir, int depth = 1)
{
try
{
string indent = new string('\t', depth);
foreach (string f in Directory.GetFiles(dir))
Console.WriteLine(indent + f.Split('\\').Last());//using split
//Console.WriteLine(indent + Path.GetFileName(f));//using Get File name
foreach (string d in Directory.GetDirectories(dir))
{
Console.WriteLine(indent + d.Split('\\').Last()); //using split
//Console.WriteLine(indent + Path.GetFileName(d)); //using Get File name
DirSearch(d, depth++);
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Hope this helps you!

Change extensions of all files in a directory

I don't get an error, but the extension isn't changed.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string filename;
string[] filePaths = Directory.GetFiles(#"c:\Users\Desktop\test\");
Console.WriteLine("Directory consists of " + filePaths.Length + " files.");
foreach(string myfile in filePaths)
filename = Path.ChangeExtension(myfile, ".txt");
Console.ReadLine();
}
}
}
Path.ChangeExtension only returns a string with the new extension, it doesn't rename the file itself.
You need to use System.IO.File.Move(oldName, newName) to rename the actual file, something like this:
foreach (string myfile in filePaths)
{
filename = Path.ChangeExtension(myfile, ".txt");
System.IO.File.Move(myfile, filename);
}
Ìf you want to change the extension of a file, call File.Move().
This only changes extension of path and not of file.
Reason: Since ChangeExtension is called of Path.ChangeExtension. For file, use System.IO. File Class and its methods.
The documentation for method ChangeExtension says that:
Changes the extension of a path string.
It doesn't say that it changes extension for a file.
I think this is roughly equivalent (correct) code:
DirectoryInfo di = new DirectoryInfo(#"c:\Users\Desktop\test\");
foreach (FileInfo fi in di.GetFiles())
{
fi.MoveTo(fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length - 1) + ".txt"); // "test.bat" 8 - 3 - 1 = 4 "test" + ".txt" = "test.txt"
}
Console.WriteLine("Directory consists of " + di.GetFiles().Length + " files.");
Console.ReadLine();

Categories