I need to parse a csv file and import it into a oracle database table. I use the Lumenworks Framework with this code:
using (CsvReader csv = new CsvReader(new StreamReader(sFile), true))
{
Console.WriteLine("test3");
}
But if I run the code, the following exception appears:
Application: Application.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.FileNotFoundException
Stack:
at Application.Program.Main(System.String[])
But the weird thing is, if I only execute the new Streamreader(sFile) part and write this on the console, no exception appears. I already debugged the sFile and this is a valid path.
If you have a new StreamReader(sFIle); and the file does not exists it will throw an exception. The path could be a valid formatted path, but if the file is not there then the exception thrown, FileNotFoundException, would make perfect sense.
Check to make sure that the file exists at the specified path before trying to open the stream.
if (File.Exists(sFIle) {
using (CsvReader csv = new CsvReader(new StreamReader(sFile), true)) {
Console.WriteLine("test3");
}
}
What a mistake. After hours I realized that the Lumenworks.dll wasn't copied to the application.exe..
Another exception than System.IO.FileNotFoundException would be truly grateful.
Related
Every 24 hours, my code auto-generates a .csv-file, writes it temporarily to an Azure directory, and finally deletes it after operating on it.
It succeeds, but from the logs I can see, that an exception is thrown.
Exception:
"The process cannot access the file 'D:\home\site\wwwroot\myFile.csv'
because it is being used by another process."
The log points to these two lines of code, where I simply specify the directory and file-name and then start a StreamWriter:
string filePath = Environment.CurrentDirectory + "\\myFile.csv"; //Specify where to create csv on hosted Azure server (not locally)
using (var w = new StreamWriter(filePath, false, new UTF8Encoding(false))) //Exception is thrown here
{
//more code
}
I am very confused, how the two above lines can result in that exception, especially since the file is always deleted after upload.
For my particular case, the problem was that the StreamWriter code was executed twice, instead of the intended once. Thanks to user TheGeneral for guiding me in the right direction in the comments.
Using Winnovative's excel library I am able to parse an excel file (xls) that contains a hyperlink. It works when the program is run directly on my machine. The exact same file will fail if I try to upload it to a website and parse it. Here is an example of the logic:
// Works when bytes are parsed from a program running locally.
// Fails when bytes are parsed from a file uploaded to a website
public void TestRead(byte[] bytes)
{
try
{
// Parse excel file
var workBook = new ExcelWorkbook(new MemoryStream(bytes));
// Save file
var toSave = workBook.Save();
System.IO.File.WriteAllBytes(#"C:\Users\[User]\Downloads\Test.xls", toSave);
}
catch (Exception e)
{
}
}
This is only an issue with xls files. I don't have trouble parsing a xlsx file with a hyperlink. The uploaded file fails to parse with an exception (which also crashes the application even though it is enclosed in a try-catch block):
Could not open the workbook.Arithmetic operation resulted in an overflow.
at Winnovative.ExcelLib.ExcelWorkbook..ctor(Stream excelStream, String openPassword, ExcelWorkbookDefaultSettings defaultSettings)
at Winnovative.ExcelLib.ExcelWorkbook..ctor(Stream excelStream)
and
System.OverflowException was unhandled
Message: An unhandled exception of type 'System.OverflowException' occurred in wnvxls.dll
Additional information: Arithmetic operation resulted in an overflow.
I'm having trouble with an error. I have searched the web but havent found an answer that made sense to me. I'm basically trying to create a temporary text file, and write to it. Here it the code concerning the error:
using ( StreamWriter output = new StreamWriter(File.Create(GetTemporaryDirectory())))
and the getTemporaryDirectory method:
public string GetTemporaryDirectory() {
string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
string tempFile = Path.ChangeExtension(tempDirectory, ".txt");
Directory.CreateDirectory(tempFile);
return tempFile;
}
and last but not least the error:
dir = C:\Users\Jack Givens\AppData\Local\Temp\5ftxwy31.txt
A first chance exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll
An unhandled exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll
Additional information: Access to the path 'C:\Users\Jack Givens\AppData\Local\Temp\0lpe1k5t.txt' is denied.
If anyone can tell me what is wrong with my code and what i need to do to fix it, I will appreciate it. side note: sorry for crappy code, i'm kinda a beginner :)
Directory.CreateDirectory(tempFile);
You have just created a directory, the name of which ends in "*.txt".
Then you attempt to create a file with the exact same path. But that's not possible.
You call CreateDirectory on your filename so now a folder exists in the path that File.Create is attempting to call. Just simply remove the Directory.CreateDirectory(tempFile); line (it is not needed as the folder is guaranteed to exist) and your code should work.
You are creating a directory, not a file. You can't open a directory as a file.
Description:
The code below is the simplest code I could write which causes the failure. I've also tried: putting the CreateFile and MoveFile in different using statements, putting them in different xaml pages, moving the file into a subdirectory with a new filename, moving it into a subdirectory with the same filename. They all throw the same exception. CopyFile throws the same exception in all circumstances.
Question is--what incredibly simple thing am I not accounting for?
Open a new Silverlight for Windows Phone 7 project targeting Windows Phone 7.1.
Open App.xaml.cs.
Paste the following lines of code into Application_Launching:
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
isf.CreateFile("hello.txt");
isf.MoveFile("hello.txt", "hi.txt");
}
Click start debugging, targeting emulator or device.
Expected: creates a file named "hello.txt", then (effectively) renames "hello.txt" to "hi.txt".
Actual: throws exception below.
System.IO.IsolatedStorage.IsolatedStorageException was unhandled
Message=An error occurred while accessing IsolatedStorage.
StackTrace:
at System.IO.IsolatedStorage.IsolatedStorageFile.MoveFile(String sourceFileName, String destinationFileName)
at PhoneApp4.App.Application_Launching(Object sender, LaunchingEventArgs e)
at Microsoft.Phone.Shell.PhoneApplicationService.FireLaunching()
at Microsoft.Phone.Execution.NativeEmInterop.FireOnLaunching()
You should call Close after you create the file.
IsolatedStorageFileStream helloFile = store.CreateFile("hello.txt");
helloFile.Close();
isf.MoveFile("hello.txt", "hi.txt");
I was just having the same issue, but the solution is simple:
The target file must not exists, delete it before the moving. Make sure the target file is not open anywhere before deleting.
The source file must not be open anywhere.
if (_isolatedStorage.FileExists(targetPath))
{
_isolatedStorage.DeleteFile(targetPath);
}
_isolatedStorage.MoveFile(sourcePath, targetPath);
Perfectly execute this piece of code
var file = await ApplicationData.Current.LocalFolder.GetFileAsync(oldName);
await file.RenameAsync(newName);
MBen, your answer is not correct. Calling Close on the file does not fix this error. I am seeing the exact same error as well even though I call "Close" before MoveFile.
edit Ok just figured out the problem I was having - if you try to call MoveFile when the destinationFile already exists, it throws an Exception. You have to delete the destinationFile first before moving your sourceFile to it.
Documentation says:
// Summary:
// Creates a new file, writes the specified string to the file, and then closes
// the file. If the target file already exists, it is overwritten.
First line, first sentence: Creates a new file, and on the exceptions it lists:
// System.IO.FileNotFoundException:
// The file specified in path was not found.
In which case would this happen? If it always create a file then it shouldn't thrown a FileNotFoundException...
Is the documentation wrong? Or is it missing a <remarks> tag perhaps?
File.WriteAllText eventually calls:
private static void InternalWriteAllText(string path, string contents, Encoding encoding)
{
using (StreamWriter streamWriter = new StreamWriter(path, false, encoding))
{
streamWriter.Write(contents);
}
}
All of the exceptions thrown prior to the call to InternalWriteAllText throw ArgumentException or ArgumentNullException but theoretically (since FileStream can throw the exception) the streamWriter.Write(contents); could potentially throw the exception. Very unlikely though based on what it does and how the streamWriter is opened.
I wouldn't necessarily say the doc is wrong per se, more that MS is covering their butt by documenting the (very rare) possibility.
Source: Decompiling mscorlib v4.0.0.0 using ILSpy.
UPDATE
Just checked mscorlib v2.0.0.0, same case except it contains fewer sanity checks (meaning it basically translates directly to the code above).