透過 C# 來刪除唯讀檔案,可以透過 FileInfo 或 FileAttribute 取消唯讀後再進行
FileInfo 取消唯讀
FileInfo 取消唯讀
using System;
using System.IO;
namespace ReadOnlyFileDelete
{
class Program
{
static void Main(string[] args)
{
string targetFileFullName = @"D:\Demo.txt";
if (!File.Exists(targetFileFullName))
throw new FileNotFoundException();
// 利用 FileInfo
FileInfo fi = new FileInfo(targetFileFullName);
if (fi.IsReadOnly) fi.IsReadOnly = false;
fi.Delete();
}
}
}
FileAttribute 取消唯讀
using System;
using System.IO;
namespace ReadOnlyFileDelete
{
class Program
{
static void Main(string[] args)
{
string targetFileFullName = @"D:\Demo.txt";
if (!File.Exists(targetFileFullName))
throw new FileNotFoundException();
FileAttributes attributes = File.GetAttributes(targetFileFullName);
if (attributes.HasFlag(FileAttributes.ReadOnly))
{
attributes = attributes & ~FileAttributes.ReadOnly;
File.SetAttributes(targetFileFullName, attributes);
}
File.Delete(targetFileFullName);
}
}
}
沒有留言:
張貼留言