我厌倦了将包含特定字符串的文件从一个文件夹复制到另一个文件夹,但它一直给我错误消息System.IO.IOException:进程无法访问文件'Z:\ Upload \ Text-File-1.txt '因为它被另一个进程使用。尝试过一些东西,但没有任何作用。不知道如何解决它。
using System;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
CheckandMoveFiles();
}
private static void CheckandMoveFiles()
{
//put filenames in array
string[] sourcePath = Directory.GetFiles(@"Z:\Upload\");
string targetPath = @"Z:\Upload\TextFiles\";
try
{
//Get each filepath and check for string
foreach (string name in sourcePath)
{
string d = "Text";
if (name.Contains(d))
{
string fileName = name;
string sourceFile = System.IO.Path.Combine(sourcePath.ToString(), fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
using (StreamReader reader = new StreamReader(sourceFile))
{
File.Copy(sourceFile, destFile, true);
}
}
}
}
catch (IOException ex)
{
Console.WriteLine(ex); // Write error
}
Console.WriteLine("****************************DONE***************************************");
Console.ReadLine();
}
}
}
答案 0 :(得分:0)
using (StreamReader reader = new StreamReader(sourceFile))
{
File.Copy(sourceFile, destFile, true);
}
您打开StreamReader
阅读sourceFile
,然后尝试File.Copy()
它?这就是你收到错误的原因
丢失StreamReader,你不需要它
File.Copy(sourceFile, destFile, true);
会做什么
答案 1 :(得分:0)
应该是这样的:
if (name.Contains(d))
{
string fileName = name;
string sourceFile = System.IO.Path.Combine(sourcePath.ToString(), fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
File.Copy(sourceFile, destFile, true);
}
File.Copy将文件路径作为参数而不是指向文件的流。
答案 2 :(得分:0)
试试这位朋友......
public class SimpleFileCopy
{
static void Main()
{
string fileName = "test.txt";
string sourcePath = @"C:\Users\Public\TestFolder";
string targetPath = @"C:\Users\Public\TestFolder\SubDir";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
System.IO.File.Copy(sourceFile, destFile, true);
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
foreach (string s in files)
{
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(s, destFile, true);
}
}
else
{
Console.WriteLine("Source path does not exist!");
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
答案 3 :(得分:0)
您的问题看起来如下:
string sourceFile = System.IO.Path.Combine(sourcePath.ToString(), fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
因为fileName
已经包含完整路径,而sourcePath
是一个字符串数组,所以sourcePath.ToString()
不会产生您期望的路径。
而是尝试:
string sourceFile = fileName;
string destFile = System.IO.Path.Combine(targetPath, System.IO.Path.GetFileName(fileName));