文件操作

1.判断文件是否处于打开状态下

[DllImport("kernel32.dll")]
        public static extern IntPtr _lopen(string file, int readwrite);

        [DllImport("kernel32.dll")]
        public static extern bool CloseHandle(IntPtr hObject);

        public const int OF_READWRITE = 2;
        public const int OF_SHARE_DENY_NONE = 0x40;
        public static readonly IntPtr HFILE_ERROR = new IntPtr(-1);

        public static bool isFileOpen(string file)
        {
            if (!File.Exists(file))
                return false;
            IntPtr vhandle = _lopen(file, OF_READWRITE | OF_SHARE_DENY_NONE);
            if (vhandle == HFILE_ERROR)
                return true;
            CloseHandle(vhandle);
            return false;
        }

 2.保存成csv文件

private void button1_Click(object sender, EventArgs e)
        {
            
            string path = @"d:aa.csv";
            if (isFileOpen(path))
            {
                MessageBox.Show("文件处于打开状态,无法写入.");
                return;
            } 
            StreamWriter sw = new StreamWriter(path, true, Encoding.UTF8);
            for (int i = 0; i < 100; i++)
                sw.WriteLine($"第{i}次,aaaa,bbbb,cccc,");//中间用逗号隔开,可以分多个栏位
            sw.Flush();
            sw.Close();

        }
原文地址:https://www.cnblogs.com/yagzh2000/p/13600791.html