除了其他可能导致此错误的原因外:
您不能在完整的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
的值是什么? - JustinfileName
是空的。 - Jeremy McGee