2017-11-15 5 views
1

C#では2つの別々のテキストファイルを読み込む方法があり、新しいテキストフォルダに新しいテキストファイルがありますか?おそらくそれらを調べるために常にループしていますか?2つのテキストファイルを読み込んで新しいテキストファイルを新しいtxtファイルに送信する

+0

はいです。 FileStreamとFileSystemWatcherを調べてください。 – DonBoitnott

+2

ファイルの "LastModified"タイムスタンプよりも正確なものがコンテンツ内にない限り、新しいものを見るためにそれらを読む必要はありません –

答えて

1

あなたは新しいしているかを判断するために、ファイルのGetLastWriteTimeプロパティを使用することができ、そして、あなたは新しいフォルダにそれを置くためにFile.Copy(またはFile.Move)を使用することができます。

static void CopyNewestFileToLocation(string fileOne, string fileTwo, string destination) 
{ 
    // Argument validation 
    if (fileOne == null) throw new ArgumentNullException(nameof(fileOne)); 
    if (fileTwo == null) throw new ArgumentNullException(nameof(fileTwo)); 
    if (destination == null) throw new ArgumentNullException(nameof(destination)); 

    if (!File.Exists(fileOne)) throw new FileNotFoundException(
     "File specified for fileOne parameter does not exist", fileOne); 
    if (!File.Exists(fileTwo)) throw new FileNotFoundException(
     "File specified for fileTwo parameter does not exist", fileTwo); 

    if (!Directory.Exists(destination)) 
    { 
     try 
     { 
      Directory.CreateDirectory(destination); 
     } 
     catch (Exception e) 
     { 
      var msg = $"Unable to create specified directory: {destination}" + 
         $"\nException Details:\n{e}"; 

      throw new ArgumentException(msg); 
     } 
    } 

    // Find newest file and copy it 
    if (File.GetLastWriteTime(fileOne) > File.GetLastWriteTime(fileTwo)) 
    { 
     File.Copy(fileOne, Path.Combine(destination, Path.GetFileName(fileOne))); 
    } 
    else // TODO: decide what to do if they're equal 
    { 
     File.Copy(fileTwo, Path.Combine(destination, Path.GetFileName(fileTwo))); 
    } 
} 

使用例

CopyNewestFileToLocation(@"f:\public\temp\temp.txt", @"f:\public\temp\temp2.txt", 
    @"f:\public\temp\newLocation"); 
+0

書き込み時間が同じ場合はどうなりますか時間? – hellyale

+0

これはelseにヒットします。 – Aaron

+0

実際、多くの改善点がありますが、これは簡単なサンプルです。 –

関連する問題