C# File and Directory iteration, possible to do both at one? - c#

This might be a confusing question but I have written below a Directory crawler, that will start at a root crawler, find all unique directories and then find all files and count them and add up their file size. However, the way I have it written requires going to the directory twice, one to find the directories and the next time to count the files. If/how is it possible to get all the information once?
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
HashSet<string> DirectoryHolding = new HashSet<string>();
DirectoryHolding.Add(rootDirectory);
#region All Directory Region
int DirectoryCount = 0;
int DirectoryHop = 0;
bool FindAllDirectoriesbool = true;
while (FindAllDirectoriesbool == true)
{
string[] DirectoryHolder = Directory.GetDirectories(rootDirectory);
if (DirectoryHolder.Length == 0)
{
if (DirectoryHop >= DirectoryHolding.Count())
{
FindAllDirectoriesbool = false;
}
else
{
rootDirectory = DirectoryHolding.ElementAt(DirectoryHop);
}
DirectoryHop++;
}
else
{
foreach (string DH in DirectoryHolder)
{
DirectoryHolding.Add(DH);
}
if (DirectoryHop > DirectoryHolding.Count())
{
FindAllDirectoriesbool = false;
}
rootDirectory = DirectoryHolding.ElementAt(DirectoryHop);
DirectoryHop++;
}
}
DirectoryCount = DirectoryHop - 2;
#endregion
#region File Count and Size Region
int FileCount = 0;
long FileSize = 0;
for (int i = 0; i < DirectoryHolding.Count ; i++)
{
string[] DirectoryInfo = Directory.GetFiles(DirectoryHolding.ElementAt(i));
for (int fi = 0; fi < DirectoryInfo.Length; fi++)
{
try
{
FileInfo fInfo = new FileInfo(DirectoryInfo[fi]);
FileCount++;
FileSize = FileSize + fInfo.Length;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}
}
The stopwatch result for this is 1.38
int FileCount = 0;
long FileSize = 0;
for (int i = 0; i < DirectoryHolding.Count; i++)
{
var entries = new DirectoryInfo(DirectoryHolding.ElementAt(i)).EnumerateFileSystemInfos();
foreach (var entry in entries)
{
if ((entry.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
{
DirectoryHolding.Add(entry.FullName);
}
else
{
FileCount++;
FileSize = FileSize + new FileInfo(entry.FullName).Length;
}
}
}
the stop watch for this method is 2.01,
this makes no sense to me.
DirectoryInfo Dinfo = new DirectoryInfo(rootDirectory);
DirectoryInfo[] directories = Dinfo.GetDirectories("*.*", SearchOption.AllDirectories);
FileInfo[] finfo = Dinfo.GetFiles("*.*", SearchOption.AllDirectories);
foreach (FileInfo f in finfo)
{
FileSize = FileSize + f.Length;
}
FileCount = finfo.Length;
DirectoryCount = directories.Length;
.26 seconds i think this is the winner

You can use Directory.EnumerateFileSystemEntries():
var entries = Directory.EnumerateFileSystemEntries(rootDirectory);
foreach (var entry in entries)
{
if(File.Exists(entry))
{
//file
}
else
{
//directory
}
}
Or alternatively DirectoryInfo.EnumerateFileSystemInfos() (this might be more performant since FileSystemInfo already has most of the info you need and you can skip the File.Exists check):
var entries = new DirectoryInfo(rootDirectory).EnumerateFileSystemInfos();
foreach (var entry in entries)
{
if ((entry.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
{
//direcotry
}
else
{
//file
}
}

The usual approach is to write a recursive method. Here it is in pseudocode:
void ProcessDirectory(Dir directory)
{
foreach (var file in directory.Files)
ProcessFile(file);
foreach (var child in directory.Subdirectories)
ProcessDirectory(directory);
}
You can also reverse the order of the foreach loops. For example, to calculate the total size of all files with a recursive method, you could do this:
int GetTotalFileSize(Dir directory)
{
ulong result = 0UL;
foreach (var child in directory.Subdirectories)
result += GetTotalFileSize(directory);
foreach (var file in directory.Files)
result += file.Length;
return result;
}

Related

How can I use indexof and substring to find words in a string?

In the constructor :
var tempFR = File.ReadAllText(file);
GetResults(tempFR);
Then :
private List<string> GetResults(string file)
{
List<string> results = new List<string>();
string word = textBox1.Text;
string[] words = word.Split(new string[] { ",," }, StringSplitOptions.None);
for(int i = 0; i < words.Length; i++)
{
int start = file.IndexOf(words[i], 0);
results.Add(file.Substring(start));
}
return results;
}
words contains in this case 3 words System , public , test
I want to find all the words in file and add them to the list results using indexof and substring.
The way it is now start value is -1 all the time.
To clear some things.
This is a screenshot of the textBox1 :
That is why I'm using two commas to split and get the words.
This screenshot showing the words after split them from the textBox1 :
And this is the file string content :
I want to add to the List results all the words in the file.
When looking at the last screenshot there should be 11 results.
Three time the word using three times the word system five times the word public.
but the variable start is -1
Update :
Tried Barns solution/s but for me it's not working good.
First the code that make a search and then loop over the files and reporting to backgroundworker :
int numberofdirs = 0;
void DirSearch(string rootDirectory, string filesExtension, string[] textToSearch, BackgroundWorker worker, DoWorkEventArgs e)
{
List<string> filePathList = new List<string>();
int numberoffiles = 0;
try
{
filePathList = SearchAccessibleFilesNoDistinct(rootDirectory, null, worker, e).ToList();
}
catch (Exception err)
{
}
label21.Invoke((MethodInvoker)delegate
{
label21.Text = "Phase 2: Searching in files";
});
MyProgress myp = new MyProgress();
myp.Report4 = filePathList.Count.ToString();
foreach (string file in filePathList)
{
try
{
var tempFR = File.ReadAllText(file);
_busy.WaitOne();
if (worker.CancellationPending == true)
{
e.Cancel = true;
return;
}
bool reportedFile = false;
for (int i = 0; i < textToSearch.Length; i++)
{
if (tempFR.IndexOf(textToSearch[i], StringComparison.InvariantCultureIgnoreCase) >= 0)
{
if (!reportedFile)
{
numberoffiles++;
myp.Report1 = file;
myp.Report2 = numberoffiles.ToString();
myp.Report3 = textToSearch[i];
myp.Report5 = FindWordsWithtRegex(tempFR, textToSearch);
backgroundWorker1.ReportProgress(0, myp);
reportedFile = true;
}
}
}
numberofdirs++;
label1.Invoke((MethodInvoker)delegate
{
label1.Text = string.Format("{0}/{1}", numberofdirs, myp.Report4);
label1.Visible = true;
});
}
catch (Exception err)
{
}
}
}
I have the words array already in textToSearch and the file content in tempFR then I'm using the first solution of Barns :
private List<string> FindWordsWithtRegex(string filecontent, string[] words)
{
var res = new List<string>();
foreach (var word in words)
{
Regex reg = new Regex(word);
var c = reg.Matches(filecontent);
int k = 0;
foreach (var g in c)
{
Console.WriteLine(g.ToString());
res.Add(g + ":" + k++);
}
}
Console.WriteLine("Results of FindWordsWithtRegex");
res.ForEach(f => Console.WriteLine(f));
Console.WriteLine();
return res;
}
But the results I'm getting in the List res is not the same output in Barns solution/s this is the results I'm getting the List res for the first file :
In this case two words system and using but it found only the using 3 times but there is also system 3 times in the file content. and the output format is not the same as in the Barns solutions :
Here is an alternative using Regex instead of using IndexOf. Note I have created my own string to parse, so my results will be a bit different.
EDIT
private List<string> FindWordsWithCountRegex(string filecontent, string[] words)
{
var res = new List<string>();
foreach (var word in words)
{
Regex reg = new Regex(word, RegexOptions.IgnoreCase);
var c = reg.Matches(filecontent).Count();
res.Add(word + ":" + c);
}
return res;
}
Simple change this part and use a single char typically a space not a comma:
string[] words = word.Split(' ');
int start = file.IndexOf(words[i],0);
start will be -1 if the word is not found.
MSDN: IndexOf(String, Int32)
for(int i = 0; i < words.Length; i++)
{
int start = file.IndexOf(words[i], 0);
// only add to results if word is found (index >= 0)
if (start >= 0) results.Add(file.Substring(start));
}
If you want all appearance of the words you need an extra loop
int fileLength = file.Length;
for(int i = 0; i < words.Length; i++)
{
int startIdx = 0;
while (startIdx < fileLength ){
int idx = file.IndexOf(words[i], startIdx]);
if (start >= 0) {
// add to results
results.Add(file.Substring(start));
// and let Word-search continue from last found Word Position Ending
startIdx = (start + words.Length);
}
}
int start = file.IndexOf(words[i], 0);
// only add to results if word is found (index >= 0)
if (start >= 0) results.Add(file.Substring(start));
}
MayBe you want a caseinsensitiv search
file.IndexOf(words[i], 0, StringComparison.CurrentCultureIgnoreCase); MSDN: StringComparer Class

Parallel folder size scanning. WaitAll() hangs

I think I get that this is hanging because I am not awaiting the async call from Main causing a deadlock but I cant make Main async so how to fix this? I will first show the program I am trying to parallelize then I will show my attempt at parallelization. I think it is obvious I am trying to get the fastest possible program to check the size of a list of folders (from multiple shares). If it is possible to parallelize at a higher level and write the outputs to CSV out of order that is fine but I was satisfied with processing one share at a time. I have tried several derivations of the parallel code. This is just my latest so it is possible it is more wrong than my earlier attempts. Just know that this was not my only attempt. I am currently knee deep in researching parallelization in c# and will probably be able to figure this out at some point but if you can offer insights that would be greatly appreciated
namespace ShareSize
{
class Program
{
static long Size { get; set; }
static void Main(string[] args)
{
using (StreamReader sr = new StreamReader(args[0]))
{
while (!sr.EndOfStream)
{
share = sr.ReadLine().Trim(',');
Console.WriteLine(share);
string[] root = Directory.GetDirectories(share);
MeasureFolders(root);
MeasureFiles(Directory.GetFiles(share));
Console.WriteLine("SIZE = " + Size);
using (StreamWriter sw = new StreamWriter(args[1], true))
{
sw.WriteLine(share + "," + Size / 1073741824);
}
Size = 0;
}
}
Console.ReadLine();
}
private static MeasureFolders(string[] root)
{
MeasureFolder(root);
}
private static MeasureFolder(string[] directories)
{
foreach (string d in directories)
{
try
{
Console.WriteLine($"Measure Folder {d}");
string[] files = Directory.GetFiles(d);
string[] subDirectories = Directory.GetDirectories(d);
if (files.Length != 0)
MeasureFiles(files);
if (subDirectories.Length != 0)
MeasureFolder(subDirectories);
}
catch
{
;
}
}
}
private static void MeasureFiles(string[] files)
{
foreach (var f in files)
{
Size += new FileInfo(f).Length;
}
}
}
}
And here is my attempt at parallelization.
namespace ShareSize
{
class Program
{
static long Size { get; set; }
static List<Task> Tasks = new List<Task>();
private static Object Lock = new Object();
static void Main(string[] args)
{
string share = "";
using (StreamReader sr = new StreamReader(args[0]))
{
while (!sr.EndOfStream)
{
share = sr.ReadLine().Trim(',');
string[] root = Directory.GetDirectories(share);
MeasureFolders(root).ConfigureAwait(false);
MeasureFiles(Directory.GetFiles(share));
using (StreamWriter sw = new StreamWriter(args[1], true))
{
sw.WriteLine(share + "," + Size / 1073741824);
}
Size = 0;
}
}
Console.ReadLine();
}
private static async Task MeasureFolders(string[] root)
{
await MeasureFolder(root).ConfigureAwait(false);
await Task.WhenAll(Tasks.ToArray());
}
private static async Task MeasureFolder(string[] directories)
{
foreach (string d in directories)
{
try
{
string[] files = Directory.GetFiles(d);
string[] subDirectories = Directory.GetDirectories(d);
if (files.Length != 0)
{
Task newTask = new Task(delegate { MeasureFiles(files); });
newTask.Start();
Tasks.Add(newTask);
}
if (subDirectories.Length != 0)
await MeasureFolder(subDirectories);
}
catch
{
;
}
}
}
private static void MeasureFiles(string[] files)
{
foreach (var f in files)
{
lock (Lock)
{
try
{
Size += new FileInfo(f).Length;
}
catch
{
;
}
}
}
}
}
}
Thank you very much.
Maybe I am missing the point, but the above seems a bit over-complicated. The below code snippets get the directory size of any given path. I wrote the code in such a way that comparing the serialized code to the parallelized code is easier. But one of the biggest things to consider: If you are going to collect data in parallel, you will likely need to allocate memory ahead of time (array), or lock the object to ensure no concurrent access (lock() { }). Both are demonstrated below.
Notes:
This code can be optimized further
Getting the size on disk would require a few changes
This uses built-in C# Parallel.For, Parallel.Foreach, and lock() {} syntax
SerialFunctions
public long GetDirectorySizesBytes(string root) {
long dirsize = 0;
string[] directories = Directory.GetDirectories(root);
string[] files = Directory.GetFiles(root);
if (files != null) {
dirsize += GetFileSizesBytes(files);
}
foreach(var dir in directories) {
var size = GetDirectorySizesBytes(dir);
dirsize += size;
}
return dirsize;
}
public long GetFileSizesBytes(string[] files) {
long[] fileSizes = new long[files.Length];
for(int i = 0; i < files.Length; i++) {
fileSizes[i] = new FileInfo(files[i]).Length;
}
return fileSizes.Sum();
}
Parallelized Functions
public long ParallelGetDirectorySizesBytes(string root) {
long dirsize = 0;
string[] directories = Directory.GetDirectories(root);
string[] files = Directory.GetFiles(root);
if (files != null) {
dirsize += ParallelGetFileSizesBytes(files);
}
Parallel.ForEach(directories, dir => {
var size = ParallelGetDirectorySizesBytes(dir);
lock (lockObject) { //static lockObject defined at top of class
dirsize += size;
}
});
return dirsize;
}
public long ParallelGetFileSizesBytes(string[] files) {
long[] fileSizes = new long[files.Length];
Parallel.For(0, files.Length, i => {
fileSizes[i] = new FileInfo(files[i]).Length;
});
return fileSizes.Sum();
}
Test function
[TestMethod]
public void GetDirectoriesSizesTest() {
var actual = GetDirectorySizesBytes(#"C:\Exchanges");
var parallelActual = ParallelGetDirectorySizesBytes(#"C:\Exchanges");
long expected = 25769767281;
Assert.AreEqual(expected, actual);
Assert.AreEqual(expected, parallelActual);
}
Complete Class
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace StackOverflowProjects.Tests {
[TestClass]
public class DirectorySizeTests {
public static object lockObject = new object();
[TestMethod]
public void GetDirectoriesSizesTest() {
var actual = GetDirectorySizesBytes(#"C:\Exchanges");
var parallelActual = ParallelGetDirectorySizesBytes(#"C:\Exchanges");
long expected = 25769767281;
Assert.AreEqual(expected, actual);
Assert.AreEqual(expected, parallelActual);
}
public long GetDirectorySizesBytes(string root) {
long dirsize = 0;
string[] directories = Directory.GetDirectories(root);
string[] files = Directory.GetFiles(root);
if (files != null) {
dirsize += GetFileSizesBytes(files);
}
foreach(var dir in directories) {
var size = GetDirectorySizesBytes(dir);
dirsize += size;
}
return dirsize;
}
public long GetFileSizesBytes(string[] files) {
long[] fileSizes = new long[files.Length];
for(int i = 0; i < files.Length; i++) {
fileSizes[i] = new FileInfo(files[i]).Length;
}
return fileSizes.Sum();
}
public long ParallelGetDirectorySizesBytes(string root) {
long dirsize = 0;
string[] directories = Directory.GetDirectories(root);
string[] files = Directory.GetFiles(root);
if (files != null) {
dirsize += ParallelGetFileSizesBytes(files);
}
Parallel.ForEach(directories, dir => {
var size = ParallelGetDirectorySizesBytes(dir);
lock (lockObject) {
dirsize += size;
}
});
return dirsize;
}
public long ParallelGetFileSizesBytes(string[] files) {
long[] fileSizes = new long[files.Length];
Parallel.For(0, files.Length, i => {
fileSizes[i] = new FileInfo(files[i]).Length;
});
return fileSizes.Sum();
}
}
}

How to allow directory program code to only display the differences between directory paths for C# Windows Application?

For this section of the code, I'm comparing each of the directories as entered by the user. Currently, the codes lists all files within each directory. I was looking for a way to list only the files and folders that are different and not present with one folder, but is in the other.
Code:
private void btnCompare_Click(object sender, EventArgs e)
{
// Clear previous results.
dgvFiles.Rows.Clear();
// Get sorted lists of files in the directories.
string dir1 = txtDir1.Text;
if (!dir1.EndsWith("\\")) dir1 += "\\";
string[] file_names1 = Directory.GetFileSystemEntries(dir1, "*",
SearchOption.AllDirectories); ;
for (int i = 0; i < file_names1.Length; i++)
{
file_names1[i] = file_names1[i].Replace(dir1, "*.*");
}
Array.Sort(file_names1);
string dir2 = txtDir2.Text;
if (!dir2.EndsWith("\\")) dir2 += "\\";
string[] file_names2 = Directory.GetFileSystemEntries(dir2, "*",
SearchOption.AllDirectories);
for (int i = 0; i < file_names2.Length; i++)
{
file_names2[i] = file_names2[i].Replace(dir2, "*.*");
}
Array.Sort(file_names2);
// Compare.
int i1 = 0, i2 = 0;
while ((i1 < file_names1.Length) && (i2 < file_names2.Length))
{
if (file_names1[i1] == file_names2[i2])
{
// They match. Display them both.
dgvFiles.Rows.Add(new Object[] { file_names1[i1], file_names2[i2] });
i1++;
i2++;
}
else if (file_names1[i1].CompareTo(file_names2[i2]) < 0)
{
// Display the directory 1 file.
dgvFiles.Rows.Add(new Object[] { file_names1[i1], null });
i1++;
}
else
{
// Display the directory 2 file.
dgvFiles.Rows.Add(new Object[] { null, file_names2[i2] });
i2++;
}
It is pretty simple with Linq.
// Get all entries in file_name1 not in file_names2
var diff1 = file_names1.Except(file_names2);
// Get all entries in file_name2 not in file_names1
var diff2 = file_names2.Except(file_names1);
// Union the two diffs
var result = diff1.Union(diff2);
// Get files in both directory
var common = file_names1.Intersect(file_names2);
foreach(string file in common)
dgvFiles.Rows.Add(new Object[] { file, file });
foreach(string file in diff1)
dgvFiles.Rows.Add(new Object[] { file, null });
foreach(string file in diff2)
dgvFiles.Rows.Add(new Object[] { null, file });

How to compare between two directories and get the missing files? c# winform

Thats the code :
enter code here
private void button1_Click(object sender, EventArgs e)
{
try
{
string[] Folder1 = Directory.GetFiles(txtFolder1.Text, comboBox1.SelectedItem.ToString());
string[] Folder1FileNames = new string[Folder1.Length];
int c = 0;
string fname1;
foreach (string f in Folder1)
{
fname1 = Path.GetFileName(f);
Folder1FileNames[c] = fname1;
c++;
}
string fname2;
string[] Folder2 = Directory.GetFiles(txtFolder2.Text, comboBox1.SelectedItem.ToString());
string[] Folder2FileNames = new string[Folder2.Length];
int t = 0;
foreach (string f in Folder2)
{
fname2 = Path.GetFileName(f);
Folder2FileNames[t] = fname2;
t++;
}
int m=0;
foreach (string f in Folder1FileNames)
{
while (f != Folder2FileNames[m] && m < Folder2FileNames.Length)
{
m++;
if (m == Folder2FileNames.Length)
{
Label newlabe = new Label();
newlabe.Text = f;
if(!listBox1.Items.Contains(newlabe.Text))
{
listBox1.Items.Add(newlabe.Text);
}
}
}
m = 0;
}
}
catch (Exception ex)
{
label1.Text = ex.Message;
}
I created two arrays that contains Files From SourceDirectory(Folder1) and CompareDirectory(Folder2) , then more 2 arrays that contains the files name with out the full ptah (in order to compare between the araays) ,then i have tried to compare between the arrays ,and add the missing file to the list box .
the problem is that when I tried it it gave me the first missing file from the source folder , (e.g source folder contains the next files : a.txt,b.txt,c.txt,d.txt and compare folder contains:a.txt,b.txt , the result in the list box will be c.txt , and the label will show:"you are out of the array index" )
what should i do ?
thanks!
You can go with a bit simpler and tidier solution, something like that should work:
var dir1Files = Directory
.EnumerateFiles(txtFolder1.Text, "*", SearchOption.AllDirectories)
.Select(Path.GetFileName);
var dir2Files = Directory
.EnumerateFiles(txtFolder2.Text, "*", SearchOption.AllDirectories)
.Select(Path.GetFileName);
var diffs = dir1Files.Except(dir2Files).Distinct().ToArray();
listBox1.Items.AddRange(diffs);
thank you guys , i succeeded to do it in my way.
thats my old code :
int m=0;
foreach (string f in Folder1FileNames)
{
while (f != Folder2FileNames[m] && m < Folder2FileNames.Length)
{
m++;
if (m == Folder2FileNames.Length)
{
Label newlabe = new Label();
newlabe.Text = f;
if(!listBox1.Items.Contains(newlabe.Text))
{
listBox1.Items.Add(newlabe.Text);
}
}
}
m = 0;
}
the new one is :`
int m = 0;
foreach (string f in Folder1FileNames)
{
m = 0;
while (f != Folder2FileNames[m] && m < Folder2FileNames.Length-1)
{
m++;
if (m == Folder2FileNames.Length-1)
{
if (Folder2FileNames[m] != f)
{
Label newlabe = new Label();
newlabe.Text = f;
if (!listBox1.Items.Contains(newlabe.Text))
{
listBox1.Items.Add(newlabe.Text);
}
}
}
}
}
now its working well,in this way im not out of the array index
// Find the set difference between the two folders.
// For this example we only check one way.
var queryList1Only = (from file in list1
select file).Except(list2, myFileCompare);
Console.WriteLine("The following files are in list1 but not list2:");
foreach (var v in queryList1Only)
{
Console.WriteLine(v.FullName);
}
See full example

i get an error "System.Array does not contain a definition for LastWriteTime"

I am having a problem with my c# code I can't seem to get my if statement to work I think it is trying to reference the wrong part of code for some reason. I have checked that I have all the right references in and all the right uses in. I have pasted the offending code bellow:
FolderBrowserDialog dlg2 = new FolderBrowserDialog();
if (dlg2.ShowDialog() == DialogResult.OK)
//do whatever with dlg.SelectedPath
{
string searchPattern = "*";
DirectoryInfo source = new DirectoryInfo(dlg.SelectedPath);
DirectoryInfo target = new DirectoryInfo(dlg2.SelectedPath);
DirectoryInfo dir = new DirectoryInfo(dlg.SelectedPath);
FileInfo[] fi = dir.GetFiles("*", SearchOption.AllDirectories);
{
if (fi.LastWriteTime.Date == DateTime.Today.Date)
{
FileInfo[] sourceFiles = source.GetFiles(searchPattern, SearchOption.AllDirectories);
for (int i = 0; i < sourceFiles.Length; ++i)
File.Copy(sourceFiles[i].FullName, target.FullName + "\\" + sourceFiles[i].Name, true);
}
}
any help that could be given would be gratefully appreciated thanks.
What you want to do is probably this?
FileInfo[] fis = dir.GetFiles("*", SearchOption.AllDirectories);
foreach (FileInfo fi in fis)
{
if (fi.LastWriteTime.Date == DateTime.Today.Date)
{
FileInfo[] sourceFiles = source.GetFiles(searchPattern, SearchOption.AllDirectories);
for (int i = 0; i < sourceFiles.Length; ++i)
File.Copy(sourceFiles[i].FullName, target.FullName + "\\" + sourceFiles[i].Name, true);
}
}
Well, fi is an array so fi.LastWriteTime.Date == DateTime.Today.Date would give that error. Correctly.
You don't seem to use the returned directories for anything else, so I'm not able to suggest a 'fix'.
You are calling LastWriteTime on the array, and an array doesn't have this property.
You need to call LastWriteTime on the members of the array, e.g.
fi[0].LastWriteTime
Or to iterate over all the files:
foreach(var file in fi)
{
if(file.LastWriteTime.Date == DateTime.Today.Date)
{
....
}
}
Error is simple you are using LastWriteTime on array instead of the FileInfo item. You should use an index in the code like this:
fi[0].LastWriteTime.Date ///your code
replace 0 with your index num or use it in a foreach loop like this:
foreach(var item in fi)
{
if (item.LastWriteTime.Date == DateTime.Today.Date)
{
FileInfo[] sourceFiles = source.GetFiles(searchPattern, SearchOption.AllDirectories);
for (int i = 0; i < sourceFiles.Length; ++i)
File.Copy(sourceFiles[i].FullName, target.FullName + "\\" + sourceFiles[i].Name, true);
}
}
As previously stated, this Property is invalid on an array.
Just enclose your FileInfo with a foreach loop:
foreach(FileInfo fi in dir.GetFiles("*", SearchOption.AllDirectories))
{
if (fi.LastWriteTime.Date == DateTime.Today.Date)
{
FileInfo[] sourceFiles = source.GetFiles(searchPattern, SearchOption.AllDirectories);
for (int i = 0; i < sourceFiles.Length; ++i)
File.Copy(sourceFiles[i].FullName, target.FullName + "\\" + sourceFiles[i].Name, true);
}
}
You need
foreach(FileInfo fi in dir.GetFiles("*", SearchOption.AllDirectories))
{
if (fi.LastWriteTime.Date == DateTime.Today.Date)
{
FileInfo[] sourceFiles = source.GetFiles(searchPattern, SearchOption.AllDirectories);
for (int i = 0; i < sourceFiles.Length; ++i)
File.Copy(sourceFiles[i].FullName, target.FullName + "\\" + sourceFiles[i].Name, true);
}
}
You are missinf a for loop:
for (int i = 0; i < fi.Length; ++i)
{
if (fi[i].LastWriteTime.Date == DateTime.Today.Date)
...
}

Categories

Resources