欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c# 共享状态的文件读写实现代码

程序员文章站 2023-12-01 21:22:22
复制代码 代码如下: using system.io; using system.text; namespace lucienbao.commons { public st...
复制代码 代码如下:

using system.io;
using system.text;
namespace lucienbao.commons
{
public static class filehelper
{
public static string shareread(string file, encoding encoding)
{
string content = string.empty;
filestream fs = new filestream(file, filemode.open, fileaccess.read, fileshare.readwrite);
try
{
if (fs.canread)
{
byte[] buffer = new byte[fs.length];
fs.read(buffer, 0, buffer.length);
content = encoding.getstring(buffer);
}
}
finally
{
fs.close();
fs.dispose();
}
return content;
}
public static void shareappend(string content, string file, encoding encoding)
{
sharewrite(content, file, encoding, filemode.append);
}
public static void sharewrite(string content, string file, encoding encoding, filemode filemode)
{
filestream fs = new filestream(file, filemode, fileaccess.write, fileshare.read);
try
{
if (fs.canwrite)
{
byte[] buffer = encoding.getbytes(content);
if (buffer.length > 0)
{
fs.write(buffer, 0, buffer.length);
fs.flush();
}
}
}
finally
{
fs.close();
fs.dispose();
}
}
}
}