Winforms 读取和解析文本文件exception-C#
我正在分析大文本文件,它在一段时间内工作正常,但几分钟后它给了我异常(System.Core.dll中发生了类型为“System.UnauthorizedAccessException”的未处理异常) 其他信息:对路径的访问被拒绝。) 我在下面提到的行中得到了例外Winforms 读取和解析文本文件exception-C#,winforms,c#-4.0,Winforms,C# 4.0,我正在分析大文本文件,它在一段时间内工作正常,但几分钟后它给了我异常(System.Core.dll中发生了类型为“System.UnauthorizedAccessException”的未处理异常) 其他信息:对路径的访问被拒绝。) 我在下面提到的行中得到了例外 accessor = MemoryMapped.CreateViewAccessor(offset, length, MemoryMappedFileAccess.Read); 下面是我的功能 public static void
accessor = MemoryMapped.CreateViewAccessor(offset, length, MemoryMappedFileAccess.Read);
下面是我的功能
public static void CityStateZipAndZip4(string FilePath,long offset,long length,string spName)
{
try
{
long indexBreak = offset;
string fileName = Path.GetFileName(FilePath);
if (fileName.Contains(".txt"))
fileName = fileName.Replace(".txt", "");
System.IO.FileStream file = new System.IO.FileStream(@FilePath, FileMode.Open,FileAccess.Read, FileShare.Read );
Int64 b = file.Length;
MemoryMappedFile MemoryMapped = MemoryMappedFile.CreateFromFile(file, fileName, b, MemoryMappedFileAccess.Read, null, HandleInheritability.Inheritable, false);
using (MemoryMapped)
{
//long offset = 182; // 256 megabytes
//long length = 364; // 512 megabytes
MemoryMappedViewAccessor accessor = MemoryMapped.CreateViewAccessor(offset, length, MemoryMappedFileAccess.Read);
byte byteValue;
int index = 0;
int count = 0;
StringBuilder message = new StringBuilder();
do
{
if (indexBreak == index)
{
count = count + 1;
accessor.Dispose();
string NewRecord = message.ToString();
offset = offset + indexBreak;
length = length + indexBreak;
if (NewRecord.IndexOf("'") != -1)
{ NewRecord = NewRecord.Replace("'", "''"); }
// string Sql = "insert into " + DBTableName + " (ID, DataString) values( " + count + ",'" + NewRecord + "')";
string Code = "";
if (spName == AppConfig.sp_CityStateZip)
{
Code = NewRecord.Trim().Substring(0, 1);
}
InsertUpdateAndDeleteDB(spName, NewRecord.Trim (), Code);
accessor = MemoryMapped.CreateViewAccessor(offset, length, MemoryMappedFileAccess.Read);
message = new StringBuilder();
index = 0;
//break;
}
byteValue = accessor.ReadByte(index);
if (byteValue != 0)
{
char asciiChar = (char)byteValue;
message.Append(asciiChar);
}
index++;
} while (byteValue != 0);
}
MemoryMapped.Dispose();
}
catch (FileNotFoundException)
{
Console.WriteLine("Memory-mapped file does not exist. Run Process A first.");
}
}
此异常意味着您的程序无法从Windows中读取文件。
当您的程序尝试读取此文件时,是否已确保该文件未被锁定?
例如,它可能是您自己的程序当前正在使用的文件。
如果不是,试着以管理员的身份运行您的程序,看看它是否有什么不同。在资源处理代码的深处,我们有这样的代码:
try {
// Try loading some strings here.
} catch {
// Oops, could not load strings, try another way.
}
异常已经被抛出和处理,它将永远不会出现在您的应用程序中。查看它的唯一方法是附加调试器并观察此消息
从代码中可以看出,这与您的问题无关。这里真正的问题是调试器向您显示了一些您不应该看到的内容
在没有调试模式的情况下运行解决方案,它工作正常。我以管理员身份运行,但没有区别,我的程序工作了1分钟,然后出现异常。您能调试程序并查看异常发生的具体时间点吗?异常出现在accessor=MemoryMapped.CreateViewAccessor(偏移量、长度、MemoryMappedFileAccess.Read);