开发者

how can I copy a file with a certain date in c#

I have an issue with my code I开发者_如何学JAVA can get it to copy all the files in a directory and it's subdirectories and I have got an if statement telling it to copy a file if the modified date is the same as today but it still copy's all the files I have searched on the internet for a solution and they all come up with vague answers that are similar to the doe I already have I have pasted the code below.

DirectoryInfo source = new DirectoryInfo(dlg.SelectedPath);
DirectoryInfo target = new DirectoryInfo(dlg2.SelectedPath);

DirectoryInfo dir = new DirectoryInfo(dlg.SelectedPath);
FileInfo[] fis = dir.GetFiles("*", SearchOption.AllDirectories);
foreach (FileInfo fi in fis)
{
    if (fi.LastWriteTime.Date == DateTime.Today.Date)
    {
        FileInfo[] sourceFiles = source.GetFiles("*", SearchOption.AllDirectories);
        foreach (FileInfo fc in sourceFiles)
            if (fc.LastWriteTime.Date == DateTime.Today.Date)
                for (int i = 0; i < sourceFiles.Length; ++i)
                    File.Copy(sourceFiles[i].FullName, target.FullName + "\\" + sourceFiles[i].Name, true);
    }
}

any help will be appreciated


Shouldn't it be like this?

FileInfo[] fis = dir.GetFiles("*", SearchOption.AllDirectories);
foreach (FileInfo fi in fis)
{
    if (fi.LastWriteTime.Date == DateTime.Today.Date)
    {
        File.Copy(fi.FullName, target.FullName + "\\" + fi.Name, true);
    }
}

The thing is, right now, whenever you find a file that fulfills your condition, you copy all the files in the source folder to the target folder, which is wrong. You should only copy the files that you need.

The code above will only work for the files in the root folder, but it's easy to make it work for subfolders as well. Just make another function that finds all the subfolders in a folder and call the code above with each of the subfolders as parameters.


The precision of the DateTime on the FileSystem and in .net isn't the same.

Try Something like this:

if((Math.Abs((currentFile.LastWriteTime - DateTime.Today.Date).TotalMilliseconds) > tolerance){...}


As an alternative, you could use a LINQ query like the following:

DirectoryInfo source = new DirectoryInfo(dlg.SelectedPath);
DirectoryInfo target = new DirectoryInfo(dlg2.SelectedPath);

var files = source.GetFiles("*", SearchOption.AllDirectories).Where(file => file.LastWriteTime.Date.Equals(DateTime.Today.Date));
foreach (FileInfo file in files)
    File.Copy(file.FullName, target.FullName + "\\" + file.Name, true);


i think you are missing indentation or parenthesis after the if statement, i think it's an empty if followed by the copy statement. do

if (date == date) 
{ 
   filecopy 
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜