c# Unauthorized exception - c#

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

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

C# Console app need assistance with main args error

I have the following c# Console app I would run this in ssis but i am using a couple of PDF manipulating librarys. so i am going to call an exe from my ssis package while passing in a file path.
But i am getting the following error when trying to run via the exe.
Unhandled Exception: System.IndexOutOfRangeException: Index was
outside the bounds of the array. at ConsoleApp.program.Main(String[]
args) line 87
BUT if i run in debug it works fine. Once i get it working on its own via the exe, i want to pass the filepath as a parameter in ssis.
see c# below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using org.apache.pdfbox.pdmodel;
using org.apache.pdfbox.util;
using System.IO;
namespace PDF_Read_ConsoleApp
{
class Program
{
public static void FilePath(string path)
{
//Console.WriteLine("Please enter full pdf path \n\n ");
//path = Console.ReadLine();
string fp;
fp = #path;
string[] files = Directory.GetFiles(path, "*.pdf");
foreach (string s in files)
{
string txtOutput = s.Replace(".pdf", ".txt");
if (File.Exists(txtOutput))
{
File.Delete(txtOutput);
}
string output;
PDDocument doc = null;
try
{
doc = PDDocument.load(s);
PDFTextStripper stripper = new PDFTextStripper();
stripper.getText(doc);
output = stripper.getText(doc);
StreamWriter NewFile;
NewFile = new StreamWriter(txtOutput);
//NewFile.Write(output.ToString());
NewFile.Write(output.ToString());
NewFile.Close();
}
finally
{
//if (doc != null)
//{
doc.close();
// Console.WriteLine("\n\n File saveed - ({0} ", txtOutput);
//}
}
}
}
static void Main(string[] args)
{
args[0] = #"C:\SSIS_Packages\PDF_Import\PDF_Import\PO_pdfs"; //// TESTING FILE PATH1
FilePath(args[0]);
}
}
}
Kind Regards
Rob
I have managed to get it working, I need to enter an argument within the debug screen, see information in URL below
Console app arguments, how arguments are passed to Main method
THank you for everyone's comments

C# load folder names

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.

check if WMI namespace exists from c#

I want to check if a certain feature is installed on a certain machine.
I have a powershell code that checks this, and now I want to check this from .net code.
I can see that in the cmdlet, the code checks if there is an invalid namespace error.
When searching the web, I found the following code:
ManagementClass myClass = new ManagementClass(scope, path, getOptions);
try
{
myClass.get();
}
catch (System.Management.Exception ex)
{
if (ex.ErrorCode == ManagementStatus.InvalidNamespace)
{
return true;
}
}
...
I want to clean this code a bit, so basically I have 2 questions:
Is there another way to check for an InvalidNamespace error? (The code I've copied was later used to invoke some method within myClass, so I wonder if I can somehow achieve my goal in a more direct way)
Do I really need the parameter getOptions?
To get all the wmi namespaces, you must first connect to the root namespace and then query for all the __NAMESPACE instances, and for each instance recursively repeat this process. about the getOptions parameter which is a ObjectGetOptions class is not necessary in this case, so can be null.
Check this code to get all the wmi namespaces (you can populate a list with that info and then check if the namespace exist in the machine)
using System;
using System.Collections.Generic;
using System.Text;
using System.Management;
namespace MyConsoleApplication
{
class Program
{
static private void GetWmiNameSpaces(string root)
{
try
{
ManagementClass nsClass = new ManagementClass( new ManagementScope(root), new ManagementPath("__namespace"), null);
foreach (ManagementObject ns in nsClass.GetInstances())
{
string namespaceName = root + "\\" + ns["Name"].ToString();
Console.WriteLine(namespaceName);
//call the funcion recursively
GetWmiNameSpaces(namespaceName);
}
}
catch (ManagementException e)
{
Console.WriteLine(e.Message);
}
}
static void Main(string[] args)
{
//set the initial root to search
GetWmiNameSpaces("root");
Console.ReadKey();
}
}
}

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