C#将复制的文件保存到文本文件中

本文关键字:文件 文本 保存 复制 | 更新日期: 2023-09-27 18:26:50

因此,在我正在制作的程序中,当文件被复制时,我想写入文本文件。然而,我必须复制文件的代码是循环的。似乎在写入文本文件时,它只在最后一个文件被复制时写入。。。不确定那里到底发生了什么,我希望我的描述能有意义。以下是一些代码。。。

//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中的文件是.jpg、b.png、c.pdf

文本文件中发生了什么:日期:2013年8月8日12:00:00 AM源路径:C:''X''目标路径:C:''Y''复制的文件:C.pdf

我希望发生的事情:日期:2013年8月8日12:00:00 AM源路径:C:''X''目标路径:C:''Y''复制的文件:.jpg日期:2013年8月8日12:00:00 AM源路径:C:''X''目标路径:C:''Y''复制的文件:b.png日期:2013年8月8日12:00:00 AM源路径:C:''X''目标路径:C:''Y''复制的文件:C.pdf

C#将复制的文件保存到文本文件中

您希望追加到文件中,而不是像当前那样每次都覆盖它;

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