试图在 using() 语句中的流开始之前查找

Attempted to seek before beginning of stream inside a using() statement

所以我得到了 IOException: Attempted to Seek before the beginning of the stream。但是当我查看它时,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);