csharp-filesystem

获取当前路径

String appPath = System.AppDomain.CurrentDomain.BaseDirectory;

String appPath = System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName)

设置工作路径

System.IO.Directory.SetCurrentDirectory(App.appPath + "\\openssl");
...
// 恢复默认路径
System.IO.Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

AppData 文件夹

Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)

监控目录

// 是否开始监控
private bool isMonitor = false;
// 最后一次修改文件的大小
private Int64 file_size = 0;
// 最后一条的时间,用来判断是否是重复记录
private string lastDatetime = "";
private List<DateTime> lastWriteTime = new List<DateTime>();

FileSystemWatcher watcher = new FileSystemWatcher();


watcher.Path = App.db.m_config[0].MonitorPath;
watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size;
// Only watch csv files.
watcher.Filter = "*.csv";
// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnFileChanged);
// Begin watching.
watcher.EnableRaisingEvents = true;
watcher.IncludeSubdirectories = true;

lastWriteTime.Add(DateTime.MinValue);
lastWriteTime.Add(DateTime.MinValue);
lastWriteTime.Add(DateTime.MinValue);


public void OnFileChanged(object source, FileSystemEventArgs e)
{
System.IO.FileInfo file = new System.IO.FileInfo(e.FullPath);
var size = file.Length;//大小",

if (size != 0 && file_size != size)
{
file_size = size;
Log.Information($"changed file,file_size={file_size},size={size}");
System.Threading.Thread.Sleep(1000);
Dispatcher.Invoke(new Action(() => { doBusi(e.FullPath); }));
}
}

int type = 0;
if (msg.EndsWith("P13.txt"))
{
type = 1;
}else if (msg.EndsWith("P14.txt"))
{
type = 2;
}
else if (msg.EndsWith("P15.txt"))
{
type = 3;
}
if (type >=1 && type <= 3)
{
DateTime wt = File.GetLastWriteTime(msg);

if (lastWriteTime[type - 1] != wt)
{
Log.Information($"start Convert file,file={msg}");

Thread.Sleep(80);
Protocol.CmdType = (int)ModelProtocol.eCmdType.DATAS;
Protocol.Param = $"{msg}|{App.db.m_config[0].SavePath}";
nng_plugin.send(JsonConvert.SerializeObject(Protocol));

Dispatcher.Invoke(new Action(
() => { Log2ui(LOG_TYPE_INFO, $"开始计算:{msg}"); }
));
lastWriteTime[type - 1] = wt;
}
}

选择文件

System.Windows.Forms.OpenFileDialog fileDialog = new System.Windows.Forms.OpenFileDialog();
fileDialog.Multiselect = true;
fileDialog.Title = "请选择要转换的文件";
fileDialog.Filter = "csv files (*.csv)|*.csv|所有文件(*.*)|*.*";
if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
files = fileDialog.FileNames;
}else
{
return;
}

文件另存为


删除

try
{
System.IO.File.Delete(shortcutPath);
}
catch (System.IO.IOException e)
{
Console.WriteLine(e.Message);
Log.Error($"delete shortcut failed. msg={e.Message}");
return false;
}

// Delete a directory and all subdirectories with Directory static method...
if(System.IO.Directory.Exists(@"C:\Users\Public\DeleteTest"))
{
try
{
System.IO.Directory.Delete(@"C:\Users\Public\DeleteTest", true);
}
catch (System.IO.IOException e)
{
Console.WriteLine(e.Message);
}
}

// 删除到回收站 using Microsoft.VisualBasic.FileIO;
FileSystem.DeleteDirectory(NextFolder.FullName, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);

遍历文件

DirectoryInfo TheFolder=new DirectoryInfo(folderFullName);
//遍历文件
foreach(FileInfo NextFile in TheFolder.GetFiles())
this.listBox2.Items.Add(NextFile.Name);

//遍历文件夹
foreach(DirectoryInfo NextFolder in TheFolder.GetDirectories())
this.listBox1.Items.Add(NextFolder.Name);

//遍历文件
foreach (FileInfo file in TheFolder.GetFiles("*.csv"))
{
list_files.Add(file.FullName);
}

文件夹是否存在

string strPath = "F:\\notebook\\haha\\";//路径的正确写法
if (Directory.Exists(strPath))
{
MessageBox.Show("存在文件夹");
//Directory.Delete(strPath, false);//如果文件夹中有文件或目录,此处会报错
//Directory.Delete(strPath, true);//true代表删除文件夹及其里面的子目录和文件
}
else
{
MessageBox.Show("不存在文件夹");
Directory.CreateDirectory(strPath);
}

文件是否存在

//判断文件的存在、创建、删除文件
string dddd = aaaa + "11.txt";
if (File.Exists(dddd))
{
MessageBox.Show("存在文件");
File.Delete(dddd);//删除该文件
}
else
{
MessageBox.Show("不存在文件");
File.Create(dddd);//创建该文件,如果路径文件夹不存在,则报错。
}

另存为文件,获取路径

使用 win32

使用了这个库,可以再 nuget 里面添加

Windows-API-Code-Pack

CommonOpenFileDialog dialog = new CommonOpenFileDialog();
dialog.InitialDirectory = App.appPath;
dialog.IsFolderPicker = true;
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
cert_store_path = dialog.FileName;
tb_cert_save_path.Text = cert_store_path;
}

使用 winforms

using System.Windows.Forms;

// 选择文件
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Title = "选择文件";
openFileDialog.Filter = "zip文件|*.zip|rar文件|*.rar|所有文件|*.*";
openFileDialog.FileName = string.Empty;
openFileDialog.FilterIndex = 1;
openFileDialog.RestoreDirectory = true;
openFileDialog.DefaultExt = "zip";
DialogResult result = openFileDialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.Cancel)
{
return;
}
string fileName = openFileDialog.FileName;

// 选择路径
FolderBrowserDialog m_Dialog = new FolderBrowserDialog();
DialogResult result = m_Dialog.ShowDialog();

if (result == System.Windows.Forms.DialogResult.Cancel)
{
return;
}
string m_Dir = m_Dialog.SelectedPath.Trim();
this.textBox1.Text = m_Dir;

读取文件

// .net core gb2312 不支持问题
System.Text.EncodingProvider provider = System.Text.CodePagesEncodingProvider.Instance;
Encoding.RegisterProvider(provider);

string text = System.IO.File.ReadAllText(file);
// 中文乱码时,可以指定编码后读取
string text = System.IO.File.ReadAllText(fileFullPath, Encoding.GetEncoding("gb2312"));

byte[] Buffer = ASCIIEncoding.ASCII.GetBytes(text);


// Example #2
// Read each line of the file into a string array. Each element
// of the array is one line of the file.
string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\WriteLines2.txt");

读取最后一行

try
{
lastLine = System.IO.File.ReadLines(changeFile, Encoding.GetEncoding("gb2312")).Last();
}catch
{

}

写入文件

// 写二进制文件
private BinaryWriter bw = null;
bw = new BinaryWriter(File.Open($"{AppDomain.CurrentDomain.BaseDirectory}\\uploader.h264", FileMode.Append));
byte[] data
bw.Write(data);
bw.Flush();
bw.Close();

// 写文本
File.WriteAllText(App.appPath + "\\openssl\\serverUse.cnf", cnf_prefix);

// UTF8 with BOM
File.WriteAllText($"{App.appPath}\\collog.csv", sb.ToString(), new System.Text.UTF8Encoding(true));

// 写入 gb2312 编码文件, 安装 System.Text.Encoding.CodePages
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
File.WriteAllText($"{App.appPath}\\collog.csv", sb.ToString(), Encoding.GetEncoding("GB2312"));

FileStream fs = null;
var br = new BinaryReader(fs);

BinaryWriter

using System;
using System.IO;

class ConsoleApplication
{
const string fileName = "AppSettings.dat";

static void Main()
{
WriteDefaultValues();
DisplayValues();
}

public static void WriteDefaultValues()
{
using (BinaryWriter writer = new BinaryWriter(File.Open(fileName, FileMode.Create)))
{
writer.Write(1.250F);
writer.Write(@"c:\Temp");
writer.Write(10);
writer.Write(true);
}
}

public static void DisplayValues()
{
float aspectRatio;
string tempDirectory;
int autoSaveTime;
bool showStatusBar;

if (File.Exists(fileName))
{
using (BinaryReader reader = new BinaryReader(File.Open(fileName, FileMode.Open)))
{
aspectRatio = reader.ReadSingle();
tempDirectory = reader.ReadString();
autoSaveTime = reader.ReadInt32();
showStatusBar = reader.ReadBoolean();
}

Console.WriteLine("Aspect ratio set to: " + aspectRatio);
Console.WriteLine("Temp directory is: " + tempDirectory);
Console.WriteLine("Auto save time set to: " + autoSaveTime);
Console.WriteLine("Show status bar: " + showStatusBar);
}
}
}

文件信息

FileInfo fi = new FileInfo(file.FullName);
var fileDay = fi.LastWriteTime.ToString("yyyy-MM-dd");

获取、修改文件的创建、修改时间


新建文件

// .net core 需要下面两行支持 gb2312
System.Text.EncodingProvider provider = System.Text.CodePagesEncodingProvider.Instance;
Encoding.RegisterProvider(provider);

FileStream fs = new FileStream(storePath, FileMode.Create);
StreamWriter sw = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));

string strLine = "";
foreach (var it in listDatas)
{
strLine = "";
for (int i = 0; i < channel_count; ++i)
{
strLine += String.Format("{0:0.0000}", it[i]) + ",";
}
strLine = strLine.Remove(strLine.Length - 1);
strLine += "\r\n";
sw.Write(strLine);
}
sw.Flush();
sw.Close();
fs.Close();

追加文件

 FileStream fs = new FileStream(distPath, FileMode.Append);
StreamWriter sw = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
sw.WriteLine(writeValues);
sw.Flush();
sw.Close();

拷贝文件

string OrignFile,NewFile; 
OrignFile = Server.MapPath(".")+"\\myText.txt";
NewFile = Server.MapPath(".")+"\\myTextCopy.txt";
File.Copy(OrignFile,NewFile,true);

删除文件

string delFile = Server.MapPath(".")+"\\myTextCopy.txt"; 
File.Delete(delFile);

// 删除到回收站 using Microsoft.VisualBasic.FileIO;
FileSystem.DeleteFile(NextFile.FullName, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);

移动文件/重命名

string OrignFile,NewFile; 
OrignFile = Server.MapPath(".")+"\\myText.txt";
NewFile = Server.MapPath(".")+"\\myTextCopy.txt";
File.Move(OrignFile,NewFile);

string oldName = "D:\myfolder\myfile.txt";
string newName = "D:\myfolder\mynewfile.txt";
System.IO.File.Move(oldName, newName);

获取应用版本信息

//遍历文件夹
DirectoryInfo TheFolder = new DirectoryInfo(App.appPath + @"\drivers");
foreach (DirectoryInfo NextFolder in TheFolder.GetDirectories())
{
var dr_name = NextFolder.Name;
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(App.appPath + @"\drivers\" + NextFolder.Name + @"\"+ NextFolder.Name+".exe");
m_drivers.Add(new Model_driver { Name= NextFolder.Name ,Version = fvi.ProductVersion,Comment=fvi.FileDescription});
}

调用外部程序

try
{
// call python plugin
Process p = new Process();
p.StartInfo = new ProcessStartInfo(App.appPath + @"\plugin\python_plugin.exe");
p.StartInfo.Arguments = App.appPath + @"\plugin\run.py";
p.StartInfo.WorkingDirectory = App.appPath + @"\plugin\";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
// p.Start();
}catch(Exception ex)
{
Log.Error("load python plugin failed. " + ex.Message);
}

获取返回结果

// 启动 算法插件
Process pc = new Process();
pc.StartInfo.CreateNoWindow = true;//隐藏dos窗口运行
pc.StartInfo.UseShellExecute = false;
pc.StartInfo.FileName = App.appPath + "\\openssl\\make_cert.bat";
//设置启动动作,确保以管理员身份运行
pc.StartInfo.Verb = "runas";
pc.StartInfo.RedirectStandardOutput = true;
// comment for debug only
#if DEBUG
pc.Start();
#endif
var ret = pc.StandardOutput.ReadToEnd() + Environment.NewLine;
// 恢复默认路径
System.IO.Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

压缩,解压

SharpZipLib

//  example: CreateTarGZ(@"c:\temp\gzip-test.tar.gz", @"c:\data");
private void CreateTarGZ(string tgzFilename, string sourceDirectory)
{
Stream outStream = File.Create(tgzFilename);
Stream gzoStream = new GZipOutputStream(outStream);
TarArchive tarArchive = TarArchive.CreateOutputTarArchive(gzoStream);

// Note that the RootPath is currently case sensitive and must be forward slashes e.g. "c:/temp"
// and must not end with a slash, otherwise cuts off first char of filename
// This is scheduled for fix in next release
tarArchive.RootPath = sourceDirectory.Replace('\\', '/');
if (tarArchive.RootPath.EndsWith("/"))
tarArchive.RootPath = tarArchive.RootPath.Remove(tarArchive.RootPath.Length - 1);

AddDirectoryFilesToTar(tarArchive, sourceDirectory, true);

tarArchive.Close();
}

private void AddDirectoryFilesToTar(TarArchive tarArchive, string sourceDirectory, bool recurse)
{
// Optionally, write an entry for the directory itself.
// Specify false for recursion here if we will add the directory's files individually.
TarEntry tarEntry = TarEntry.CreateEntryFromFile(sourceDirectory);
tarArchive.WriteEntry(tarEntry, false);

// Write each file to the tar.
string[] filenames = Directory.GetFiles(sourceDirectory);
foreach (string filename in filenames)
{
tarEntry = TarEntry.CreateEntryFromFile(filename);
tarArchive.WriteEntry(tarEntry, true);
}

if (recurse)
{
string[] directories = Directory.GetDirectories(sourceDirectory);
foreach (string directory in directories)
AddDirectoryFilesToTar(tarArchive, directory, recurse);
}
}