0
我有一個WindowsForm,它有一個DataGridView,顯示我的應用程序的輸出。帶按鈕的類是DriveRecursion_Results.cs。我需要它,以便一旦用戶按下按鈕,我的SanitizeFileNames類中的方法FileCleanUp()就會被調用。我不太清楚如何做到這一點。從另一個類的按鈕調用我的類和方法
下面是這兩個類代碼:
public partial class DriveRecursion_Results : Form
{
public DriveRecursion_Results()
{
InitializeComponent();
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
public void DriveRecursion(string retPath)
{
//recurse through files. Let user press 'ok' to move onto next step
// string[] files = Directory.GetFiles(retPath, "*.*", SearchOption.AllDirectories);
string pattern = " *[\\~#%&*{}/<>?|\"-]+ *";
//string replacement = "";
Regex regEx = new Regex(pattern);
string[] fileDrive = Directory.GetFiles(retPath, "*.*", SearchOption.AllDirectories);
List<string> filePath = new List<string>();
dataGridView1.Rows.Clear();
try
{
foreach (string fileNames in fileDrive)
{
if (regEx.IsMatch(fileNames))
{
string fileNameOnly = Path.GetFileName(fileNames);
string pathOnly = Path.GetDirectoryName(fileNames);
DataGridViewRow dgr = new DataGridViewRow();
filePath.Add(fileNames);
dgr.CreateCells(dataGridView1);
dgr.Cells[0].Value = pathOnly;
dgr.Cells[1].Value = fileNameOnly;
dataGridView1.Rows.Add(dgr);
filePath.Add(fileNames);
}
else
{
DataGridViewRow dgr2 = new DataGridViewRow();
dgr2.Cells[0].Value = "No Files To Clean Up";
dgr2.Cells[1].Value = "";
}
}
}
catch (Exception e)
{
StreamWriter sw = new StreamWriter(retPath + "ErrorLog.txt");
sw.Write(e);
}
}
private void button1_Click(object sender, EventArgs e)
{
//i want to call SanitizeFileName's method FileCleanup here.
}
}
這裏是SanitizeFileNames:
public class SanitizeFileNames
{
public void FileCleanup(List<string>filePath)
{
string regPattern = "*[\\~#%&*{}/<>?|\"-]+*";
string replacement = "";
Regex regExPattern = new Regex(regPattern);
foreach (string files2 in filePath)
{
try
{
string filenameOnly = Path.GetFileName(files2);
string pathOnly = Path.GetDirectoryName(files2);
string sanitizedFileName = regExPattern.Replace(filenameOnly, replacement);
string sanitized = Path.Combine(pathOnly, sanitizedFileName);
//write to streamwriter
System.IO.File.Move(files2, sanitized);
}
catch (Exception ex)
{
//write to streamwriter
}
}
}
}
SWeko具有正確的語法。你是在App_Code中還是在一個單獨的程序集中使用SanitizeFileNames? – 2010-06-24 17:39:22
但我需要在DriveRecursion路徑中引用filePath,以便我的FileCleanup()方法可以執行文件重命名。我如何從其他類引用filePath? – yeahumok 2010-06-24 17:39:32
@yeahumok - 調用者(按鈕點擊事件)必須將其傳入。DriveRecursion如何調用?由於click事件處理程序位於同一個類中,因此它也應該有權訪問路徑信息。 – GalacticCowboy 2010-06-24 17:45:23