我收到以下异常
Error Message:The process cannot access the file '....\folder\r.js' because it is being used by another process. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize)
at System.IO.StreamReader..ctor(String path, Encoding encoding)
at System.IO.File.ReadAllLines(String path, Encoding encoding)
at System.IO.File.ReadAllLines(String path)
at PrepareEventDates()
我的方法:
protected HashSet<string> PrepareEventDates()
{
HashSet<string> str = new HashSet<string>();
WebClient webclient = new WebClient();
string path = System.Configuration.ConfigurationSettings.AppSettings.Get("sss").ToString();
webclient.DownloadFile(path, Server.MapPath("r.js"));
String[] JSLines = System.IO.File.ReadAllLines(Server.MapPath("folder/r.js"));
String strDate = string.Empty;
string toolTip = string.Empty;
for (int i = 0; i < JSLines.Length; i++)
{
string result = JSLines[i];
int methodBodyStart = JSLines[i].IndexOf("DefineEvent(");
if (methodBodyStart >= 0)
{
methodBodyStart += "DefineEvent(".Length;
int methodBodyEnd = JSLines[i].LastIndexOf(')');
if (methodBodyEnd >= 0)
{
string methodBody = JSLines[i].Substring(methodBodyStart, methodBodyEnd - methodBodyStart);
var twoParams = methodBody.Split(',')
.Select(x => x.Trim(' ', '\'')).Take(2);
result = string.Join("|", twoParams.ToArray());
}
}
str.Add(result);
}
return str;
}
答案 0 :(得分:2)
问题与FileShare
选项有关,正如您在StackTrace错误中看到的那样,用于读取行的方法使用FileStream
对象。
我建议您阅读该文件,但自己实例化FileStream
:
string contents = string.Empty;
using(FileStream fs = new FileStream("", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (StreamReader sr = new StreamReader(fs))
contents = sr.ReadToEnd();