我無法創建在Visual C#一個簡單的應用程序,即執行以下操作:Visual C# - 當程序運行時如何將資源中的文件複製到磁盤中的文件夾?
- 大聲疾呼的固執尋求特定的進程。
- 當該進程開始運行時,將資源複製到文件夾。
- 當過程結束時,將另一個資源複製到該文件夾。
我試過使用定時器+線程,沒有成功。我認爲BackgroundWorker在這裏會有所幫助,但文檔相當不清楚。這是我當前的代碼:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Resources;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace ResourceCopyApp
{
public partial class MainWindow : Window {
BackgroundWorker bw;
bool pcRunning = false;
public MainWindow() {
InitializeComponent();
bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(Loop);
bw.RunWorkerAsync();
}
private void Window_Loaded(object sender, RoutedEventArgs e) {
cfgInstall.Text = Properties.Settings.Default.pcLocation;
cfgLag.Value = Properties.Settings.Default.lag;
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) {
Properties.Settings.Default.pcLocation = cfgInstall.Text;
Properties.Settings.Default.lag = (int)cfgLag.Value;
Properties.Settings.Default.Save();
}
public void Loop(object sender, DoWorkEventArgs e) {
pcRunning = false;
bool pcWasRunning = pcRunning;
if (pcRunning && !pcWasRunning) {
MessageBox.Show("Process found");
pcWasRunning = true;
Swap(true);
}
foreach (Process p in Process.GetProcesses()) {
if (p.ProcessName.Equals("Process")) {
pcRunning = true;
}
}
if (!pcRunning && pcWasRunning) {
MessageBox.Show("Process lost");
Swap(false);
}
}
public void Swap(bool v) {
byte[] file;
Thread.Sleep(new TimeSpan((long)cfgLag.Value));
if (v) {
file = Properties.Resources.NewRes;
} else {
file = Properties.Resources.BackupRes;
}
string path = cfgInstall.Text;
if (!cfgInstall.Text.EndsWith("/") && !cfgInstall.Text.EndsWith("\\")) {
path = cfgInstall.Text + "/test.txt";
}
File.WriteAllBytes(path, file);
}
}
}
發生了什麼,任何錯誤或哪些功能無法正常工作 –
當前,您的後臺工作人員只能運行一個而不是循環,因爲它的名稱會隱含。 – Michael