2017-03-02 4 views
0

Hello Stack Overflow 커뮤니티, 아직 C#의 기본 사항을 배우고 있으며 몇 가지 지침이 필요합니다. Microsoft 사이트에서 많은 자료를 읽었으며 스택 오버플로도 있지만 솔루션을 찾지 못했습니다. 내 문제는 내가 새 파일을 추가 할 때 대상 디렉터리에 쓰지 않고 추가 했으므로 File Watcher 프로그램을 설치하려고한다는 것입니다. 그것은 대상 디렉토리에 하나의 파일 만 생성 할 수 있고 생성 된 다른 새로운 파일은 덮어 쓸 수 있습니다.

다른 문제는 대상 디렉토리에 생성되는 파일을 반영하는 것입니다. 예를 들어 빈 .bmp 파일을 만들면 대상 디렉토리에 기본적으로 "whatever.txt"파일이 추가됩니다. 아래에 제 코드를 붙여 넣었고 어떤 생각을해도 환영합니다. 친절하게 SO 커뮤니티에 감사드립니다.File Watcher 및 File.copy 프로그램 혼동

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); 
    } 
} 
} 

답변

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); 

이렇게하면 각 파일은 복사 될 때 이름이 유지되지만 지정한 디렉토리로 계속 이동합니다.

+0

감사합니다. Brandon, 감사합니다. 지금 당면한 유일한 문제는 e.FullName 아래에 빨간색 구불 구불 한 선이 있다고 제안한 코드를 테스트 할 때입니다. 나는 앞으로 더 많은 테스트를 계속할 것이지만 왜 이런 일이 벌어 질지 생각할 것입니다. 다시 고마워! –

+0

@MikeTerpeza 그건 내 잘못이야, FullName 아니 FullName 있어야합니다. 이제 해결되었습니다. –

+0

걱정 마세요 @BrandonKramer, 도와 주셔서 대단히 감사합니다! –