基本上我正在尝试制作一个清空甚至删除某个文件的程序,事实上,这个文件大约是3个或4个左右的文件夹,通过macromedia文件夹,它可以是任何人的不同命名文件夹,所以这就是为什么string []文件是这样完成的,它只是检查基本上" FlashGame.sol"在macromedia文件夹之后的每个文件夹中。
我评论了我需要帮助的地方,我基本上需要清空文件的内容,或者直接删除它。
private void button1_Click(object sender, EventArgs e)
{
string path = textBox1.Text + "/AppData/Roaming/Macromedia"; //the person using the program has to type in the beginning of the directory, C:/Users/Mike for example
bool Exists = Directory.Exists(path);
try
{
if (Exists)
{
string[] files = Directory.GetFiles(path, "*FlashGame.sol", SearchOption.AllDirectories);
string[] array = files;
for (int i = 0; i < array.Length; i++)
{
string info;
string text = array[i];
using (StreamReader streamReader = new StreamReader(text))
{
info = streamReader.ReadToEnd();
//erase the contents of the file here or even delete it
}
}
}
}
catch
{
MessageBox.Show("The given directory was not found", "Error", MessageBoxButtons.OK);
}
}
答案 0 :(得分:0)
您可以这样清除文件:
System.IO.File.WriteAllText(@"file.path",string.Empty);
所以你应该把你的代码改为:
string[] files = Directory.GetFiles(path, "*FlashGame.sol", SearchOption.AllDirectories);
foreach (var file in files)
{
System.IO.File.WriteAllText(file, string.Empty);
}
另请查看Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
,其中包含当前用户的appdata目录。
也永远不会catching a Exception without handling it correctly。您已经知道,如果该目录通过您的Exists
变量存在。
答案 1 :(得分:0)
string path = Environment.ExpandEnvironmentVariables(@"%AppData%\Macromedia\"); // Example C:\Users\Mike\AppData\Roaming\Macromedia\
if (Directory.Exists(path)) {
string[] files = Directory.EnumerateFiles(path, "*FlashGame.sol", SearchOption.AllDirectories);
foreach (string file in files) {
try {
File.Delete(file);
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
}
}