在 MS Excel 中打开文件时无法写入文件
我正在向文本文件写入一些数据。我正在使用这段代码:
using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
using (TextWriter tw = new StreamWriter(fs))
{
tw.WriteLine("sample_data");
}
}
当文件通过记事本打开时,我的应用程序可以写入其中。当 MS Excel 打开此文件时,我收到以下错误:该进程无法访问文件 myfile.csv,因为它正在被另一个进程使用。什么会导致这种情况以及如何解决这个问题?
I am writing to the text file some data. I am using this code:
using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
using (TextWriter tw = new StreamWriter(fs))
{
tw.WriteLine("sample_data");
}
}
When file is opened by notepad my app can write into it. When this file is opened by MS Excel I get following error: The process cannot access the file myfile.csv because it is being used by another process. What can cause this situation and how can I solve this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
记事本打开文件,读取全部内容,然后关闭文件。您甚至可以删除在记事本中打开的文件。
另一方面,Excel 只要显示文件就会保持文件打开状态。 Excel 中可以为 Excel 格式文件启用一些特殊的共享工具。在这种情况下,我假设它是非排他性打开的。否则,Excel 以独占方式打开该文件并保持打开状态。
如果文件已被其他人以独占模式打开,则在打开时指定共享选项并不重要。
Notepad opens the file, reads in the entire contents and then closes the file. You can even delete the file that is open in notepad.
Excel on the other hand keeps the file open as long as it is displayed. There are some special sharing tools that can be enabled in Excel for excel format files. In that case I assume that it is opened non-exlusively. Otherwise Excel opens the file exclusively and keeps it open.
It doesn't matter that you specify a share option when opening, if the file is already opened by someone else in exclusive mode.
Excel 将在打开文件时锁定该文件,以防止与该文件进行交互。我解决这个问题的一种方法是编写代码来扫描本地计算机上的 excel 进程,并在访问使用 excel 打开的文件之前终止这些进程。您可以通过查看如何检查文件来确定文件是否被锁定lock? 然后在异常处理程序中运行进程终止代码。
Excel will lock the file when it is open which prevents interaction with the file. One way I worked around this is that I wrote code to scan for excel processes on the local machine and would kill those processes before accessing a file that was open with excel. You could determine if a file is locked by looking at How to check for file lock? and then running the process killing code in the exception handler.
使用 OleDB 打开 csv 文件并使用 INSERT 和/或 UPDATE 语句。
Open the csv file using OleDB and use INSERT and/or UPDATE statements.