文件流写入异常,,,,非常奇怪的问题~!!!!! 高人进来~~
taoyi 2005-06-17 10:21:21 由于使用XmlDocument类操作XML文件出现共享冲突的问题,所以我从XmlDocument类继承了一个类,并覆盖了XmlDocument类的Load和Save方法,希望以此解决多个进程同时访问XML时出现共享冲突的问题,代码如下:
public class XmlDocumentEx : System.Xml.XmlDocument
{
public XmlDocumentEx() : base()
{
}
public new void Load(string filename)
{
FileStream fs = null;
try
{
lock(this)
{
fs = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
string str = "";
byte[] buf = new byte[fs.Length];
int len = 0;
Encoding encoding = Encoding.GetEncoding(936);
while ((len = fs.Read(buf, 0, buf.Length)) != 0)
{
str += encoding.GetString(buf);
}
base.LoadXml(str);
}
}
catch
{
throw;
}
finally
{
fs.Close();
}
}
public new void Save(string filename)
{
FileStream fs = null;
try
{
lock(this)
{
fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
Encoding encoding = Encoding.GetEncoding(936);
byte[] result = encoding.GetBytes(base.InnerXml);
fs.Write(result, 0, result.Length);
}
}
catch
{
throw;
}
finally
{
fs.Close();
}
}
}
使用这段代码后,,共享冲突的问题倒是解决了,可郁闷的是在调用Save方法写入文件的时候老是不正常,,总会多出一段,如本来内容为:
<?xml.....?>
<base>
<xx />
<..../>
<test />
</base>
结果增加一个节点后却成了:
<?xml.....?>
<base>
<xx />
<..../>
<test />
<newnode /> <--新增的节点
</base>
node /> <-- 多出一部分了
</base>
请问这是什么原因造成的,,该如何解决???几乎所有的文件操作方式我都试过了,都出问题,晕死掉了~~