(删除文件/清空文件)c#
本文关键字:文件 清空 删除 | 更新日期: 2023-09-27 18:02:10
基本上我试图使一个程序,清空甚至删除某个文件,事情是,这个文件是大约3或4左右的文件夹过去的macromedia文件夹,它可以是它不同的命名文件夹为任何人,所以这就是为什么字符串[]文件是这样做的,它只是检查基本上"FlashGame。
在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);
}
}
你可以这样清除文件:
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目录。
也永远不会捕获未正确处理的异常。您已经知道,如果目录通过Exists
变量存在
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);
}
}
}