c# 使用API函数读取ini文件,再用streamwtriter写入,读取和写入的都是同一个文件。

StreamWriter sw = new StreamWriter(path);这里会出现错误如下:
The process cannot access the file 'e:\xxx\xxx.ini' because it is being used by another process.
在网上找方法,可以通过: WritePrivateProfileString(null, null, null, filePath);来释放资源。
试过以后仍然没有效果。
哪位大神可以指教一下,非常感谢!c# C#iniAPIstreamwtriter

解决方案 »

  1.   

    ini文件你可以直接当文本读取。
      

  2.   

    把类给你好了class IniFile
        {
            // 声明INI文件的写操作函数 WritePrivateProfileString()
            [System.Runtime.InteropServices.DllImport("kernel32")]
            private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
            // 声明INI文件的读操作函数 GetPrivateProfileString()
            [System.Runtime.InteropServices.DllImport("kernel32")]
            private static extern int GetPrivateProfileString(string section, string key, string def, System.Text.StringBuilder retVal, int size, string filePath);        private string sPath = null;        public IniFile(string path)
            {
                this.sPath = path;
            }
            
            public void Write(string section, string key, string value)
            {
                // section=配置节,key=键名,value=键值,path=路径
                WritePrivateProfileString(section, key, value, sPath);
            }
            
            public string ReadValue(string section, string key)
            {
                // 每次从ini中读取多少字节
                System.Text.StringBuilder temp = new System.Text.StringBuilder(255);
                // section=配置节,key=键名,temp=上面,path=路径
                GetPrivateProfileString(section, key, "", temp, 255, sPath);
                return temp.ToString();
            }
        }
      

  3.   

    我在里面有修改,有直接的API就直接用啊。
      

  4.   

    丢了个板砖,误点,不好意思,这些我都写好了,只不过写入,我用的streamwriter。
      

  5.   

    只不过写入,我用的streamwriter。我记得写入也是有api的啊 ,为什么一起用算了呢?
      

  6.   

    我的ini格式不是很正规啊,所以不用API
      

  7.   

    GetPrivateProfileString应该是不会一直占用文件的,是不是其他程序打开了文件啊