[英]Modify a file content in C# using the Stream's API
I have a .json file who handles the user's roles and I have wrote a Repository who's responsible of adding/removing roles to users.我有一个处理用户角色的 .json 文件,我编写了一个负责向用户添加/删除角色的存储库。 The pb is that when I modify the file I want to be sure that no one access it except me.
pb 是当我修改文件时,我想确保除了我之外没有人访问它。
Here's (roughly) the code I use:这是(大致)我使用的代码:
using (var fileStream = new FileStream(_rolesFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
using (var streamReader = new StreamReader(fileStream))
using (var streamWriter = new StreamWriter(fileStream))
{
var oldContent = streamReader.ReadToEnd();
var contentObject = Deserialize(oldContent);
Modify(contentObject)
var newContent = Serialize(contentObject);
fileStream.Seek(0, SeekOrigin.Begin);
streamWriter.Write(newContent);
}
The pb with this solution is that if newContent
is a string shorter that oldContent
some characters will be remaining in the file.此解决方案的 pb 是,如果
newContent
是一个比oldContent
更短的字符串,则文件中将保留一些字符。
A solution I found is to add the following code:我找到的解决方案是添加以下代码:
using (var fileStream = new FileStream(_rolesFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
using (var streamReader = new StreamReader(fileStream))
using (var streamWriter = new StreamWriter(fileStream))
{
//...
var newContent = Serialize(contentObject);
var endPosition = fileStream.Position;
fileStream.Seek(0, SeekOrigin.Begin);
streamWriter.Write(newContent);
streamWriter.Flush();
while (fileStream.Position < endPosition)
{
streamWriter.WriteLine();
streamWriter.Flush();
}
}
It works well but does not look very clean to me.它运行良好,但对我来说看起来不太干净。 Are there any better solution who ensure that I keep the control of the file ?
有没有更好的解决方案来确保我保持对文件的控制?
Thanks in advance, Thomas提前致谢,托马斯
You can do fileStream.SetLength(fileStream.Position)
to truncate the remaining part of the file.您可以执行
fileStream.SetLength(fileStream.Position)
来截断文件的剩余部分。 This assumes that the FileStream
is left correctly positioned by the StreamWriter
after use, but that's an assumption your current code seems to be making too.这假设
FileStream
在使用后由StreamWriter
正确定位,但这是您当前代码似乎也在做出的假设。
(This is a safer assumption than the corresponding usage of StreamReader
where internal buffering may mean that the underlying stream's position is further advanced than the latest data returned by a call to a Read
method) (这是一个比
StreamReader
的相应用法更安全的假设,其中内部缓冲可能意味着底层流的位置比调用Read
方法返回的最新数据更先进)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.