c# 共享狀態(tài)的文件讀寫實(shí)現(xiàn)代碼
更新時(shí)間:2012年06月09日 00:32:05 作者:
開發(fā)中有時(shí)會(huì)遇到要對(duì)文件進(jìn)行共享狀態(tài)的讀寫操作,代碼如下,需要的朋友可以參考下
復(fù)制代碼 代碼如下:
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();
}
}
}
}
您可能感興趣的文章:
- c#實(shí)現(xiàn)數(shù)據(jù)同步的方法(使用文件監(jiān)控對(duì)象filesystemwatcher)
- C#的FileSystemWatcher用法實(shí)例詳解
- c#使用filesystemwatcher實(shí)時(shí)監(jiān)控文件目錄的添加和刪除
- c#使用filesystemwatcher監(jiān)視文件系統(tǒng)的變化
- C#采用FileSystemWatcher實(shí)現(xiàn)監(jiān)視磁盤文件變更的方法
- C#監(jiān)控文件夾變化的方法
- c# 服務(wù)器上傳木馬監(jiān)控代碼(包含可疑文件)
- C#判斷本地文件是否處于打開狀態(tài)的方法
- C#使用FileSystemWatcher控件實(shí)現(xiàn)的文件監(jiān)控功能示例
相關(guān)文章
C# 控制臺(tái)實(shí)現(xiàn)一次性輸入多行的操作
這篇文章主要介紹了C# 控制臺(tái)實(shí)現(xiàn)一次性輸入多行的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-01-01
實(shí)現(xiàn)ASP.NET無(wú)刷新下載并提示下載完成的開發(fā)思路
這篇文章主要介紹了實(shí)現(xiàn)ASP.NET無(wú)刷新下載并提示下載完成的開發(fā)思路的相關(guān)資料,需要的朋友可以參考下2015-10-10
Unity3D網(wǎng)格功能生成球體網(wǎng)格模型
這篇文章主要為大家詳細(xì)介紹了Unity3D網(wǎng)格功能生成球體網(wǎng)格模型,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-02-02
C# WindowsForm程序同時(shí)啟動(dòng)多個(gè)窗口類
這篇文章主要為大家詳細(xì)介紹了C# WindowsForm程序同時(shí)啟動(dòng)多個(gè)窗口類,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06
C#中單問(wèn)號(hào)(?)和雙問(wèn)號(hào)(??)的用法整理
本文詳細(xì)講解了C#中單問(wèn)號(hào)(?)和雙問(wèn)號(hào)(??)的用法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-05-05
C#實(shí)現(xiàn)目錄跳轉(zhuǎn)(TreeView和SplitContainer)的示例代碼
本文主要介紹了C#實(shí)現(xiàn)目錄跳轉(zhuǎn)(TreeView和SplitContainer)的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07

