我有一個windows窗體應用程序與backgroundworker(bgw)。 這BGW做一些任務,這些任務中,有這些: 第2步 - 復制文件從一個文件夾到另一個,使用下面的代碼:C#Winforms BackgroundWorker複製和更改文件System.IO .__ Error.WinIOError
public static void CopiarArquivos()
{
string fileName;
string sourcePath = System.Windows.Forms.Application.StartupPath;
const string targetPath = @"C:\CWEB\CwebIntegracaoMovel";
if (sourcePath == targetPath) return;
string destFile;
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!Directory.Exists(targetPath))
{
Directory.CreateDirectory(targetPath);
}
if (Directory.Exists(sourcePath))
{
string[] files = Directory.GetFiles(sourcePath);
//Invoke((MethodInvoker)(() => {
//});
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
FileInfo fi = new FileInfo(s);
// Use static Path methods to extract only the file name from the path.
fileName = Path.GetFileName(s);
destFile = Path.Combine(targetPath, fileName);
if (!ArquivosIguais(s, destFile) &&
(!fileName.Contains("WizardIntegracao.exe") ||
(fileName.Contains("WizardIntegracao.exe") && !File.Exists(destFile))))
{
fi.CopyTo(destFile, true);
//File.Copy(s, destFile, true);
//new System.Security.Permissions.FileIOPermission(
// System.Security.Permissions.FileIOPermissionAccess.Read, new string[] { destFile }).Demand();
}
}
}
}
複製工作正常(有一些行註釋掉正如我測試了一些其他的事情) 在BGW的步驟4,I更改這是在步驟2中複製.config文件一些設置,用下面的代碼:
public static void AlteraBaseAddress(string porta)
{
string path = "C:\\CWEB\\CwebIntegracaoMovel\\ServicoIntegracao.exe.config";
string conteudo = File.ReadAllText(path);
int inicio = conteudo.IndexOf("http://");
int fim = conteudo.IndexOf("/ServicoIntegracao/Servico");
conteudo = conteudo.Remove(inicio, fim - inicio);
conteudo = conteudo.Insert(inicio, String.Format("http://localhost:{0}", porta));
File.WriteAllText(path, conteudo);
}
當運行我的申請,我得到的例外:
Ocorreu um erro no processo de instalação do serviço:
O acesso ao caminho 'C:\CWEB\CwebIntegracaoMovel\ServicoIntegracao.exe.config' foi negado..
em System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
em System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
em System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
em System.IO.StreamWriter.CreateFile(String path, Boolean append)
em System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize)
em System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding)
雖然在嘗試更改.config文件的內容時發生錯誤,但據我所能研究,複製文件時發生錯誤,它們被我自己的應用程序鎖定,然後我無法覆蓋它的內容。
有誰知道如何使這項工作?
你應該把例外翻譯成英文,不要理解它所說的一個字。 –
@HansPassant這個.config文件不是我正在運行的主要應用程序,它是我的應用程序安裝的Windows服務(在做其他事情時) –
@KingKing對不起,因爲沒有將它翻譯成英文,所以這是「The訪問路徑'...'被拒絕...「 –