我需要使用.bin扩展名清除特定文件的内容。
我该怎么做?
答案 0 :(得分:2)
要使文件保持零大小,您可以执行以下操作:
System.IO.File.WriteAllText(@"particular.bin", String.Empty);
答案 1 :(得分:1)
它将在D:\ test目录下以递归方式删除所有带.bin扩展名的文件。
if (Directory.Exists(@"D:\test"))
{
string[] files = Directory.GetFiles(@"D:\test", "*.*", SearchOption.AllDirectories);
foreach (string file in files)
{
FileInfo fileInfo = new FileInfo(file);
if (fileInfo.Name.EndsWith(".bin"))
{
File.Delete(file);
}
}
}
答案 2 :(得分:1)
using System;
using System.Text;
using System.IO;
namespace ClearContents
{
public partial class Form1 : Form
{
private void btnClear_Click(object sender, EventArgs e)
{
//get all the files which has the .bin extension in the specified directory
string[] files = Directory.GetFiles("D:\\", "*.bin");
foreach (string f in files)
{
File.WriteAllText(f, string.Empty); //clear the contents
}
}
}
}
答案 3 :(得分:1)
此代码clears
传入的bin文件。
'clear'的含义定义为:
将传递文件中的每个字节设置为零并保留 现有文件大小
private void SetFileToZero(string inputFile)
{
// Remove previous backup file
string tempFile = Path.Combine(Path.GetDirectoryName(inputFile), "saved.bin");
if(File.Exists(tempFile)) File.Delete(tempFile);
// Get current length of input file (minus 4 byte)
FileInfo fi = new FileInfo(inputFile);
int pos = Convert.ToInt32(fi.Length) - 4;
string name = fi.FullName;
// Move the input file to "saved.bin"
fi.MoveTo(tempFile);
// Create a zero byte length file with the requested name
using(FileStream st = File.Create(name))
{
// Position the file pointer at a position 4 byte less than the required size
UTF8Encoding utf8 = new UTF8Encoding();
BinaryWriter bw = new BinaryWriter(st, utf8);
bw.Seek(pos, SeekOrigin.Begin);
// Write the last 4 bytes
bw.Write(0);
}
}
如果此位置超出实际长度,操作系统会将请求写入文件中的某个位置。为此,操作系统将文件扩展到请求的长度并用零填充。 (这真的很快,延迟几乎不可察觉)
注:出于安全原因,我制作了该文件的备份副本,并且在MoveTo之后,不要使用FileInfo var中的信息,因为它会更改以引用移动的文件。