using System;
using System.IO;
using System.Text;
namespace GeoSigmaDrawLib
{
///
/// 文件操作功能类
///
public class FileUtility
{
public const string TempPath = @".\temp\";
///
/// 文件编码
///
/// 输入文件
/// 输出文件
/// 是否成功
public static bool EncodeFile(string inputPath, string outputPath)
{
bool ret = false;
ret = File.Exists(inputPath);
//文本不存在
if (!ret)
{
return false;
}
//输入与输出文件相同
if (inputPath == outputPath)
{
return false;
}
//文本不是文本文件
ret = IsTextFile(inputPath);
string dstPath = Path.GetDirectoryName(outputPath);
if (!Directory.Exists(dstPath))
{
Directory.CreateDirectory(dstPath);
}
if (!ret)
{
File.Copy(inputPath, outputPath);
return true;
}
ret = GeoSigmaLib.EncodeFile(inputPath, outputPath);
return ret;
}
///
/// 解码文件,返回解码临时文件
///
/// 输入文件
/// 输出文件
/// 是否成功
public static bool DecodeFile(string inputPath, out string outputPath)
{
bool ret = false;
ret = File.Exists(inputPath);
if (!ret)
{
outputPath = @"";
return false;
}
string extention = Path.GetExtension(inputPath);
if (!Directory.Exists(TempPath))
{
Directory.CreateDirectory(TempPath);
}
Guid guid = Guid.NewGuid();
outputPath = Path.Combine(TempPath + guid.ToString() + extention);
//输入与输出文件相同
if (inputPath == outputPath)
{
return false;
}
//文本是文本文件
ret = IsTextFile(inputPath);
if (ret)
{
File.Copy(inputPath, outputPath);
return true;
}
else
{
ret = GeoSigmaLib.DecodeFile(inputPath, outputPath);
}
return ret;
}
///
/// Determines whether [is text file] [the specified file path].
///
/// The file path.
///
/// true if [is text file] [the specified file path]; otherwise, false.
///
public static bool IsTextFile(string filePath)
{
if (!File.Exists(filePath))
{
return false;
}
bool isBinary = false;
try
{
using (BinaryReader br = new BinaryReader(
File.Open(filePath, FileMode.Open, FileAccess.ReadWrite)
, Encoding.Default))
{
byte[] buffer = br.ReadBytes(512);
int nLength = buffer.Length;
if (nLength > 0)
{
for(int i = 0; i < nLength; i++)
{
if (buffer[i] <= 8 || buffer[i] == 11 || buffer[i] == 12 || buffer[i] == 14 || buffer[i] == 15)
{
isBinary = true;
break;
}
}
}
}
//byte[] buffer = new byte[4096]; // 定义一个缓冲区来读取文件内容
//using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
//{
// int bytesRead = fileStream.Read(buffer, 0, buffer.Length); // 读取一部分文件内容到缓冲区
// // 检查文件内容是否是二进制数据
// for (int i = 0; i < bytesRead; i++)
// {
// if (buffer[i] == 0)
// {
// return false; // 文件含有空字符,认为是二进制文件
// }
// else if (buffer[i] < 8 || (buffer[i] > 13 && buffer[i] < 32))
// {
// return false; // 文件包含非打印字符,认为是二进制文件
// }
// }
// // 如果读取的文件内容为空,则认为是二进制文件
// if (bytesRead == 0)
// {
// return false;
// }
//}
//isBinary = true;
}
catch (IOException)
{
return true; // 文件访问异常,认为是二进制文件
}
return !isBinary;
}
}
}