可能导致此错误的其他原因:
完整的PathFile字符串中不能包含某些字符。
例如,这些字符将使StreamWriter函数崩溃:
"/"
":"
可能还会有其他特殊字符使它崩溃。我发现这种情况发生在您尝试将DateTime戳放入文件名中时:
AppPath = Path.GetDirectoryName(giFileNames(0))
' AppPath is a valid path from system. (This was easy in VB6, just AppPath = App.Path & "\")
' AppPath must have "\" char at the end...
DateTime = DateAndTime.Now.ToString ' fails StreamWriter... has ":" characters
FileOut = "Data_Summary_" & DateTime & ".dat"
NewFileOutS = Path.Combine(AppPath, FileOut)
Using sw As StreamWriter = New StreamWriter(NewFileOutS , True) ' true to append
sw.WriteLine(NewFileOutS)
sw.Dispose()
End Using
防止这种麻烦的一种方法是用良性字符替换NewFileOutS中的问题字符:
' clean the File output file string NewFileOutS so StreamWriter will work
NewFileOutS = NewFileOutS.Replace("/","-") ' replace / with -
NewFileOutS = NewFileOutS.Replace(":","-") ' replace : with -
' after cleaning the FileNamePath string NewFileOutS, StreamWriter will not throw an (Unhandled) exception.
希望这可以节省一些人的头痛...!
fileName
多少?