Hello Stack Overflow社区,我还在学习c#的基础知识,需要一些指导。我在微软网站上看过很多资料,也有Stack Overflow,但没有找到解决方案。我的问题是我正在尝试设置我的文件观察程序,以便在添加新文件时,它们不会在目标目录中写入,而是添加。似乎我只能在目标目录中创建一个文件,并且创建的任何其他新文件都会被覆盖。
我的另一个挑战是反映目标目录中创建的文件。例如,如果我创建一个空白.bmp文件,目标目录将默认添加“whatever.txt”文件。我在下面粘贴了我的代码,并欢迎任何想法。非常感谢SO社区。
using System;
using System.IO;
using System.Security.Permissions;
namespace Generac_fileWatcher
{
public class FileWatcher
{
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public static void Run()
{
//string[] args = System.Environment.GetCommandLineArgs();
//// If a directory is not specified, exit program.
//if (args.Length != 2)
//{
// // Display the proper way to call the program.
// Console.WriteLine("Usage: Watcher.exe (directory)");
// return;
//}
// Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher();
//watcher.Path = args[1];
watcher.Path = @"C:\Users\mterpeza\Documents\visual studio 2012\Projects\Generac_fileWatcher\Generac_fileWatcher\FilesToWatch";
/* Watch for changes in LastAccess and LastWrite times, and
the renaming of files or directories. */
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
// Only watch text files.
watcher.Filter = "";
// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
// Begin watching.
watcher.EnableRaisingEvents = true;
// Wait for the user to quit the program.
Console.WriteLine("Press \'q\' to quit the sample.");
while (Console.Read() != 'q') ;
}
// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
// Specify what is done when a file is changed, created, or deleted.
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
File.Copy(e.FullPath, @"C:\Users\mterpeza\Documents\Visual Studio 2012\Projects\Generac_fileWatcher\Generac_fileWatcher\SyncedDirectory\whatever.txt", true);
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
// Specify what is done when a file is renamed.
Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
}
}
}
答案 0 :(得分:1)
您正在硬编码复制文件的文件名。
File.Copy(e.FullPath, @"C:\Users\mterpeza\Documents\Visual Studio 2012\Projects\Generac_fileWatcher\Generac_fileWatcher\SyncedDirectory\whatever.txt", true);
所有文件都将被复制为SyncedDirectory中的“whatever.txt”,这意味着第一个文件之后的所有文件都将被覆盖,因为目录中只能有一个具有给定名称的文件。如果您希望复制的文件使用自己的名称,则应该执行以下操作。
//note that targetDirectory does NOT contain 'whatever.txt'
var targetDirectory = @"C:\Users\mterpeza\Documents\Visual Studio 2012\Projects\Generac_fileWatcher\Generac_fileWatcher\SyncedDirectory\";
var targetPath = Path.Combine(targetDirectory, e.Name);
File.Copy(e.FullPath, targetPath, true);
这样,每个文件在复制时都会保留其名称,但仍会转到您指定的目录。