I'm trying to get all the non system files on my computer to find out what files are over 1gb via a WinForms application .
Here is the code I'm working with:
const long b500mb = 65536000;
const long b1gb = 134217728;
public Main()
{
InitializeComponent();
}
//https://unitconverter.io/gigabits/bytes/1
private void Main_Load(object sender, EventArgs e)
{
var cDriveDirectories = new DirectoryInfo(@"C:\").GetDirectories()
.Where(f => !f.Attributes.HasFlag(FileAttributes.System))
.Where(w => w.FullName != @"C:\Windows")
.Select(f => f.FullName)
.ToList();
var filesOver1Gb = new List<FileInfo>();
foreach (var item in cDriveDirectories)
{
DirectoryInfo d = new DirectoryInfo(item);
var files = d.GetFiles("*", SearchOption.AllDirectories).Where(w => w.Attributes.HasFlag(FileAttributes.Normal)
&& w.Length > b1gb).ToList();
foreach (FileInfo file in files)
{
filesOver1Gb.Add(file);
}
}
}
How can I get around this error?
System.UnauthorizedAccessException: 'Access to the path 'C:\.netpub\history' is denied.'
After @zee's help:
I VS as an admin and then put a try/catch around the line of code that was failing and continued.
This code will obtain the information I need!
const long b500mb = 65536000;
const long b1gb = 134217728;
public Main()
{
InitializeComponent();
}
//https://unitconverter.io/gigabits/bytes/1
private void Main_Load(object sender, EventArgs e)
{
var cDriveDirectories = new DirectoryInfo(@"C:\").GetDirectories()
.Where(f => !f.Attributes.HasFlag(FileAttributes.System))
.Where(w => w.FullName != @"C:\Windows")
.Select(f => f.FullName)
.ToList();
var filesOver1Gb = new List<FileInfo>();
IList<string> unauthorizedFiles = new List<string>();
foreach (var item in cDriveDirectories)
{
DirectoryInfo d = new DirectoryInfo(item);
var files = new List<FileInfo>();
try
{
files = d.GetFiles("*", SearchOption.AllDirectories).Where(w => !w.Attributes.HasFlag(FileAttributes.System)
&& w.Length > b1gb).ToList();
}
catch (UnauthorizedAccessException)
{
// ignore error and continue to process files over 1gb.
}
foreach (FileInfo file in files)
{
filesOver1Gb.Add(file);
}
}
// get the total count in bytes to find out how many gbs we have etc.
long totalOver1Gb = 0;
foreach (var file in filesOver1Gb)
{
totalOver1Gb = totalOver1Gb + file.Length;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.