在using()语句中尝试在stream开始之前进行搜索

时间:2015-05-27 10:46:50

标签: c# filestream

所以我得到了IOException:在流开始之前尝试搜索。但是当我查看它时,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;
    }

1 个答案:

答案 0 :(得分:1)

评论员是否已发布:文件小于20000字节。如果文件不够大,似乎您认为Seek将保持在0位置。它没有。在这种情况下,它会抛出ArgumentException

另一件事。 Seek将为您移动位置。无需两者兼顾。使用:

fs.Seek(-20000, SeekOrigin.End);

或设置位置:

fs.Position = fs.Length - 20000;

所以你真正想写的是:

if (fs.Length > 20000)
    fs.Seek(-20000, SeekOrigin.End);