我在 Debian 上使用 MonoDevelop,我遇到了以下代码的问题:
using (StreamReader sr = new StreamReader(File.Open(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
它在 Windows 中运行良好,在通过 MonoDevelop 运行时也很好。但是,如果我像 mono output.exe
或 sudo mono output.exe
那样运行它,第一次调用此代码的方法时它工作正常。但是第二次失败了。它不写任何东西,也不会抛出异常。我也尝试用 try catch finally
替换 using
但没有抛出异常。我认为它只是无法读取文件。
使用此代码的方法由 FileSystemWatcher 更改事件调用。我正在通过 VIM 更改文件。
有什么想法可以找出问题所在吗?为什么在 MonoDevelop 中它工作得很好(所以我无法跟踪它)并且如果从终端运行它只是第一次工作(该方法总是被调用但是文件没有被读取并且没有抛出异常它甚至没有进入内部使用{} ).
谢谢!
最佳答案
在 3.2.8 下,我遇到了一个与未触发文件观察器事件相关的不同问题(已修复的已知问题)。使用 3.12.1 或 4.0.x+ 以下代码对我来说工作正常,但它不在 R-PI 上。在您的 RPI-Debian/Mono 3.2.8 安装上试一试,看看它是否是与 R-PI 相关的错误/问题。
示例输出(Ctrl-C 退出):
>>mcs Program.cs
>>mono Program.exe
Created watcher for /var/folders/hc/xf7j8x7j72dg7g098mwkhbs40000gp/T/tmp438e6660.tmp
Changed: '/var/folders/hc/xf7j8x7j72dg7g098mwkhbs40000gp/T/tmp438e6660.tmp', type: Changed
0Changed: '/var/folders/hc/xf7j8x7j72dg7g098mwkhbs40000gp/T/tmp438e6660.tmp', type: Changed
01Changed: '/var/folders/hc/xf7j8x7j72dg7g098mwkhbs40000gp/T/tmp438e6660.tmp', type: Changed
012Changed: '/var/folders/hc/xf7j8x7j72dg7g098mwkhbs40000gp/T/tmp438e6660.tmp', type: Changed
0123Changed: '/var/folders/hc/xf7j8x7j72dg7g098mwkhbs40000gp/T/tmp438e6660.tmp', type: Changed
示例程序.cs
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace FileWatcher
{
class Program
{
static int counter = 0;
public static void Main (string[] args)
{
var tempDir = Path.GetTempPath ();
var tempFile = Path.GetTempFileName ();
var fsw = new FileSystemWatcher (tempDir, Path.GetFileName (tempFile));
fsw.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size;
fsw.Changed += WatcherOnChanged;
fsw.EnableRaisingEvents = true;
Console.WriteLine ("Created watcher for {0}", tempFile);
var cts = new CancellationTokenSource ();
Console.CancelKeyPress += (s, e) => {
e.Cancel = true;
cts.Cancel ();
};
MainAsync (tempFile, cts.Token).Wait ();
fsw.Dispose ();
File.Delete (tempFile);
}
static async Task MainAsync (string fileName, CancellationToken token)
{
while (!token.IsCancellationRequested) {
WriteFile (fileName);
Thread.Sleep (2000);
}
}
private static void WatcherOnChanged (object sender, FileSystemEventArgs eventArgs)
{
Console.WriteLine ("Changed: '{0}', type: {1}", eventArgs.FullPath, eventArgs.ChangeType);
ReadFile (eventArgs.FullPath);
}
private static void ReadFile (string fileName)
{
using (var sr = new StreamReader (File.Open (fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))) {
Console.Write (sr.ReadLine ());
}
}
private static void WriteFile (string fileName)
{
using (var sr = new StreamWriter (fileName, true)) {
sr.Write (counter++);
}
}
}
}
关于c# - 在 C# Mono Debian 中读取文件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31221171/