简体   繁体   中英

C# Saving Copied Files to a Text File

So in the program I am making I want to write to a text file when a file is copied over. However, the code I have to copy the files over are in a loop. It seems that when its time to write to the text file it only writes when the last file is copied over... Not sure whats exactly going on there and I hope my description makes sence. Here is a bit of the code...

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

Example: Say I have a source folder X to copy the contents to folder Y and say the files in folder X are a.jpg, b.png, c.pdf

What is happening in the text file: Date: 8/8/2013 12:00:00 AM Source Path: C:\\X\\ Destination Path: C:\\Y\\ File Copied: c.pdf

What I want to happen: Date: 8/8/2013 12:00:00 AM Source Path: C:\\X\\ Destination Path: C:\\Y\\ File Copied: a.jpg Date: 8/8/2013 12:00:00 AM Source Path: C:\\X\\ Destination Path: C:\\Y\\ File Copied: b.png Date: 8/8/2013 12:00:00 AM Source Path: C:\\X\\ Destination Path: C:\\Y\\ File Copied: c.pdf

You want to append to the file rather than overwriting it every time as currently happens;

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

You can also more elegantly; strSrcFile = Path.GetFileName(srcfile);

You may also like to consider stuffing the text into a StringBuilder within the loop then and writing it out once after the loop.

I see you use the same file to write log for every file copy. The problem is in way of initializing StreamWriter

new StreamWriter(GlobalVars.strLogPath);

This constructor overwrites the content of a file if it exist. If you only want to append text you have to use the following Constructor.

public StreamWriter(
    string path,
    bool append
)

Here pass true for the append parameter. ie

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM