试图在using()语句的流开始前查找
本文关键字:开始 查找 语句 using | 更新日期: 2023-09-27 17:50:50
所以我得到了IOException: trying to Seek在流开始之前。但是当我研究它的时候,seek语句是在using语句中。我可能误解了using()
,因为据我所知,在本例中,它在运行所包含的代码之前初始化了filestream
。
private string saveLocation = string.Empty;
// This gets called inside the UI to visualize the save location
public string SaveLocation
{
get
{
if (string.IsNullOrEmpty(saveLocation))
{
saveLocation = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"'Pastes";
Initializer();
}
return saveLocation;
}
set { saveLocation = value; }
}
这是它调用的函数
private void Initializer()
{
// Check if the set save location exists
if (!Directory.Exists(saveLocation))
{
Debug.Log("Save location did not exist");
try
{
Directory.CreateDirectory(saveLocation);
}
catch (Exception e)
{
Debug.Log("Failed to create Directory: " + e);
return;
}
}
// Get executing assembly
if (string.IsNullOrEmpty(executingAssembly))
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
executingAssembly = Uri.UnescapeDataString(uri.Path);
}
// Get the last received list
if (!string.IsNullOrEmpty(executingAssembly))
{
var parent = Directory.GetParent(executingAssembly);
if (!File.Exists(parent + @"'ReceivedPastes.txt"))
{
// empty using to create file, so we don't have to clean up behind ourselfs.
using (FileStream fs = new FileStream(parent + @"'ReceivedPastes.txt", FileMode.CreateNew)) { }
}
else
{
using (FileStream fs = new FileStream(parent + @"'ReceivedPastes.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
if (fs.Seek(-20000, SeekOrigin.End) >= 0)
{
fs.Position = fs.Seek(-20000, SeekOrigin.End);
}
using (StreamReader sr = new StreamReader(fs))
{
while (sr.ReadLine() != null)
{
storedPastes.Add(sr.ReadLine());
}
}
}
}
}
isInitialized = true;
}
是评注者发表的:文件小于20000字节。似乎你假设如果文件不够大,Seek
将停留在位置0。它不是。在这种情况下,它抛出ArgumentException
。
另一回事。Seek将为你移动位置。没有必要两者都做。使用:
fs.Seek(-20000, SeekOrigin.End);
或设置位置:
fs.Position = fs.Length - 20000;
所以你真正想写的是:
if (fs.Length > 20000)
fs.Seek(-20000, SeekOrigin.End);