簡體   English   中英

C#將復制的文件保存到文本文件

[英]C# Saving Copied Files to a Text File

因此,在我正在編寫的程序中,我希望在復制文件時寫入文本文件。 但是,我必須復制文件的代碼是循環的。 似乎當它寫入文本文件的時候它只會在最后一個文件被復制時寫入...不確定那里到底發生了什么,我希望我的描述有用。 這是一些代碼......

//search through the source to find the matching file
foreach (var srcfile in Directory.GetFiles(sourceDir))
{
//cut off the source file from the source path same with destination
strSrcFile = srcfile.Split(Path.DirectorySeparatorChar).Last();
strDstFile = dstfile.Split(Path.DirectorySeparatorChar).Last();

//check the files before the move 
CheckFiles(strSrcFile, strDstFile, srcfile, dstfile);

//if the destination and source files match up, replace the desination with the source
if (strSrcFile == strDstFile)
{
File.Copy(srcfile, dstfile, true);

//write to the text file 
TextWriter writer = new StreamWriter(GlobalVars.strLogPath);

writer.WriteLine("Date: " + DateTime.Today + " Source Path: " + srcfile +
                         " Destination Path: " + dstfile + " File Copied: " + strDstFile + "\n\n");
//close the writer
writer.Close();

示例:假設我有一個源文件夾X將內容復制到文件夾Y,並說文件夾X中的文件是a.jpg,b.png,c.pdf

文本文件中發生了什么:日期:8/8/2013 12:00:00 AM源路徑:C:\\ X \\目標路徑:C:\\ Y \\文件已復制:c.pdf

我想要發生的事情:日期:8/8/2013 12:00:00 AM源路徑:C:\\ X \\目標路徑:C:\\ Y \\文件已復制:a.jpg日期:2013年8月8日12: 00:00 AM源路徑:C:\\ X \\目標路徑:C:\\ Y \\文件已復制:b.png日期:8/8/2013 12:00:00 AM源路徑:C:\\ X \\目標路徑: C:\\ Y \\ File復制:c.pdf

您希望附加到文件而不是每次都像當前一樣覆蓋它;

new StreamWriter(GlobalVars.strLogPath, true); // bool append

你也可以更優雅; strSrcFile = Path.GetFileName(srcfile);

您可能還想考慮將文本填充到循環內的StringBuilder中,然后在循環后將其寫出一次。

我看到你使用相同的文件為每個文件副本寫日志。 問題在於初始化StreamWriter

new StreamWriter(GlobalVars.strLogPath);

此構造函數將覆蓋文件的內容(如果存在)。 如果您只想附加文本,則必須使用以下構造函數。

public StreamWriter(
    string path,
    bool append
)

這里為append參數傳遞true。

TextWriter writer = new StreamWriter(GlobalVars.strLogPath,true);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM