如何使用 C# 仅当文件不存在时才将文件添加到文件夹
我在文件夹“ c:\template_folder”中有一个模板文件。
在运行时,我将创建一个新文件夹“ c:\new_folder”,并且仅当文件不存在时才将模板文件复制到 new_folder 。
描述: 第一次,我会将模板文件复制到 new_folder 并用用户名重命名它...这样在第一次循环完成后,我将有 8 个 excel 文件,其中用户名作为每个文件的名称。
对于第二个循环,如果我必须将模板文件复制到 new_folder 并将其重命名为用户名,如果具有用户名的文件已经存在,则不应将文件复制到该文件夹。
我添加了代码片段以供参考。
foreach (FileInfo fi in templateFile)
{
string oldfilename = null;
string newfilename = null;
if (dir.Exists)
{
fi.CopyTo(Path.Combine(dir.ToString(), fi.Name));
FileInfo fileName = new FileInfo(fi.Name);
oldfilename = Path.Combine(dir.ToString(), fileName.ToString());
newfilename = Path.Combine(dir.ToString(), tempUserName + " " + "E" + tempUserID + " VIPv7.0.xls");
//if( !dir.ToString().Contains(newfilename))
foreach( FileInfo fileList in fileNames)
{
if (fileList.Exists == false)
File.Move(oldfilename, newfilename);
}
}
}
请帮助我完成这项工作。
谢谢 拉姆
I have a template file in a folder " c:\template_folder".
At runtime, I will create a new folder " c:\new_folder" and wish to copy the template file to the new_folder only if the file doesnt exist.
description:
for the first time, I will copy the template file to the new_folder and rename it with username... so that after first time the loop finishes, i will have 8 excel files with username as the name of the each file.
for the second loop, if I have to copy the template file to new_folder and rename it to the username, if the file with the user name already exists, then it shouldnt copy the file to the folder.
I am addin the snippet of the code for reference.
foreach (FileInfo fi in templateFile)
{
string oldfilename = null;
string newfilename = null;
if (dir.Exists)
{
fi.CopyTo(Path.Combine(dir.ToString(), fi.Name));
FileInfo fileName = new FileInfo(fi.Name);
oldfilename = Path.Combine(dir.ToString(), fileName.ToString());
newfilename = Path.Combine(dir.ToString(), tempUserName + " " + "E" + tempUserID + " VIPv7.0.xls");
//if( !dir.ToString().Contains(newfilename))
foreach( FileInfo fileList in fileNames)
{
if (fileList.Exists == false)
File.Move(oldfilename, newfilename);
}
}
}
please help me in working this.
thanks
ramm
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
仅当文件尚不存在时才有条件地移动文件,您可以这样做:
您的代码片段让我感到困惑,所以我希望我已经正确回答了您的问题。 如果我遗漏了什么,请告诉我。
To conditionally move a file only if it doesn't already exist you would do it like this:
Your code snippet confuses me, so I hope I've answered your question correctly. If I'm missing something please let me know.
您的代码对我来说似乎不正确(它无法编译),但您可以通过调用 File.Exists(filename) 检查文件是否存在,因此:
Your code doesn't seem correct to me (it doesn't compile), but you can check if a file exists by calling File.Exists(filename), so:
您想使用 File.Exists(path) 而不是注释掉的行来检查文件是否存在
You want to use File.Exists(path) instead of the commented out line to check if the file exists