I am trying to upload an excel file using webclient:
using (var client = new WebClient()) {
client.Credentials = new NetworkCredential(myname, mypassword);
byte[] responseArray = client.UploadFile(
newUri("https://www.syros.nl/prive/excel/newexcelfile.xlsx";), "POST", #"C:/Temp/~myfile.xslx");
}
Whatever I try, I keep getting an webexception:
Exception thrown: 'System.Net.WebException' in System.dll An unhandled exception of type System.Net.WebException' occurred in System.dll An exception occurred during a WebClient request.
and an inner exception:
FileNotFoundException: Could not find file 'C:\Temp\~myfile.xslx
I googled this extensively, but no one seems to have this problem.
Can someone suggest what I am doing wrong? The file is definitely present.
I tried different locations for the file, different names (with/without ~), even other/wrong credentials.
Related
I've found zero info on this anywhere and hope someone can help me.
I'm trying to send a payment processing string to Authorize.Net using standard .NET streamwriter. The language I'm using is Visual Basic but even a C# example would be appreciated!
Here's my code:
strPost = "x_FirstName=John&x_LastName=Smith&x_Phone=1234567..ETC..."
Dim myWriter As StreamWriter = Nothing
Dim objRequest As HttpWebRequest = CType(WebRequest.Create("https://secure2.authorize.net/gateway/transact.dll"), HttpWebRequest)
objRequest.Method = "POST"
objRequest.ContentLength = strPost.Length
objRequest.ContentType = "application/x-www-form-urlencoded"
Try
myWriter = New IO.StreamWriter(objRequest.GetRequestStream())
myWriter.Write(strPost)
Catch e As Exception
Return e.Message
Finally
myWriter.Close()
End Try
If I run this code and type text into the text boxes on the page (which supply the values for the strPost variable), it works fine.
However, if I enter in an international character into a textbox (such as FirstName), or copy/paste someone's name from another web page, it fails with this message:
Server Error in '/' Application.
Cannot close stream until all bytes are written.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IO.IOException: Cannot close stream until all bytes are written.
For example if the letter รก is used instead of a, it fails with the error message above.
How do I revise this code to UTF-8 or strip out those characters, etc. and stop getting that message?
Thank you in advance!
-- Chris Lee
I was able to get the solution using a recommendation from jdweng. Here's the revised code:
Dim myWriter As StreamWriter = Nothing
Dim objRequest As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
objRequest.Method = "POST"
objRequest.ContentType = "application/x-www-form-urlencoded"
Try
myWriter = New IO.StreamWriter(objRequest.GetRequestStream())
myWriter.Write(strPost)
Catch e As Exception
Return e.Message
Finally
myWriter.Flush()
myWriter.Close()
End Try
I followed this answer for my project, but failed to start because of the file not found error.
A first chance exception of type 'System.IO.FileNotFoundException' occurred in System.Drawing.dll
Additional information: File not found.
Here is my code:
PrivateFontCollection modernFont = new PrivateFontCollection();
modernFont.AddFontFile("digital.ttf");
label5.Font = new Font(modernFont.Families[0], 40);
The font file is located right in the namespace directory, is there something wrong with the the file path or else?
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.
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:
I tried the following code in MVC and received "OutputStream is not available when a custom TextWriter is used.". I followed the solution given in the URL http://blog.maartenballiauw.be/post/2008/05/ASPNET-MVC-custom-ActionResult.aspx. But my issue is not resolved.
Please help me to resolve this issue..
Code:
string json = e.ExtraParams["GridData"].ToString();
StoreSubmitDataEventArgs eSubmit = new StoreSubmitDataEventArgs(json, null);
XmlNode xml = eSubmit.Xml;
this.Response.Clear();
this.Response.ContentType = "application/vnd.ms-excel";
this.Response.AddHeader("Content-Disposition", "attachment;
filename=submittedData.xls");
XslCompiledTransform xtExcel = new XslCompiledTransform();
xtExcel.Load(Server.MapPath("Excel/XSLStyleSheet/Example2.xsl"));
xtExcel.Transform(xml, null, this.Response.OutputStream);
this.Response.End();
Error:
Server Error in '/' Application.
OutputStream is not available when a custom TextWriter is used.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: OutputStream is not available when a custom TextWriter is used.
Source Error:
Line 85: XslCompiledTransform xtExcel = new XslCompiledTransform();
Line 86: xtExcel.Load(Server.MapPath("Excel/XSLStyleSheet/Example2.xsl"));
Line 87: xtExcel.Transform(xml, null, this.Response.OutputStream); <============== ERROR LINE
Line 88: this.Response.End();
Line 89: }
#Khalid's suggestion is good. If you really want to write to Excel XML I've had good results doing stuff with the ClosedXML library.
This might sound like a simple solution, but why not just ouput your data into a CSV format. Excel has no problems opening CSV spreadsheets.