I'm trying to download a simple xml file and save it to the users local profile. When trying to download (i don't think this has anything to do with the saving location but i'm not 100% sure) i get the following exception on the webclient.
System.InvalidOperationException
My code is as follows;
public void downloadProxy() {
string url = Properties.Settings.Default.url;
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "/netsettings/proxies.xml");
try
{
WebClient GrabFile = new WebClient();
GrabFile.DownloadFile(url, path);
}
catch (WebException webEx)
{
if (webEx.Status == WebExceptionStatus.ConnectFailure)
{
Console.WriteLine("Are you behind a firewall? If so, go through the proxy server.");
}
}
}
If you are on a Windows operating system, use a backslash (not a slash) as folder separator:
\netsettings\proxies.xml
Related
I'm working on a program in C# which downloads a file from a remote server. I set up the connection (like I did for the upload function) like this:
void execute_scp_download(ScpClient scpclient, string remoteFilePath, string targetPath) {
var downloadFilestream = File.OpenWrite(targetPath);
try {
scpclient.Download(remoteFilePath, downloadFilestream);
scpclient.Disconnect();
} catch (Exception e) {
log_error("download could not be done: " + e);
}
}
scpclient gets created in the calling method where I can successfully write scpclient.Connect() without any problems.
But when I try to download a file it'll throw an exception:
30.07.2020 11:08:02 Error: download could not be done: Renci.SshNet.Common.ScpException: scp: /usr/local/etc/cert.der
at Renci.SshNet.ScpClient.ReadString(Stream stream)
at Renci.SshNet.ScpClient.InternalDownload(IChannelSession channel, Stream input, FileSystemInfo fileSystemInfo)
at Renci.SshNet.ScpClient.Download(String filename, FileInfo fileInfo)
at SMGWUpdateTool.Form1.execute_scp_download(ScpClient scpclient, String remoteFilePath, String targetPath) in C:\bla\myscript.cs Line:226.
(I translated some of the words but none of the exception itself)
I have no clue why this doesn't work. It looks like it is an problem with the target file. The remote server is a BusyBox/Linux while my client is running on Windows 10.
Is there any way to fix this?
I am attempting to open an Imanage document, in MS Word, within a temporary test application (for debugging) to later copy over into an ActiveX control project. The error that is popping up is:
Exception thrown at 0x7618851A (msvcrt.dll) in w3wp.exe: 0xC0000005: Access >violation reading location 0x09801000.
If there is a handler for this exception, the program may be safely continued.
The error occurs when running the cmd.Execute line and I am unsure as to why I am getting the error.
using IManage;
using IMANEXTLib;
using System;
namespace WebApplication3
{
public partial class WebForm2 : System.Web.UI.Page
{
IManDatabase imanagedatabase;
IManDMS myDMS = new ManDMSClass();
protected void Page_Load(object sender, EventArgs e)
{
openImanageDoc("docNumber", "versionNumber", "server", "database", ReadOnly);
}
public void imanageLogin(string server, string database)
{
try
{
IManSession session = myDMS.Sessions.Add(server);
IManWorkArea oWorkArea = session.WorkArea;
session.TrustedLogin();
foreach (IManDatabase dbase in session.Databases)
{
if (dbase.Name == database)
{
imanagedatabase = dbase;
}
}
}
catch (Exception ex)
{
throw ex;
}
}
public void openImanageDoc(string docNo, string versionNo, string server, string database, bool isReadOnly = true)
{
IManDocument doc;
try
{
imanageLogin(server, database);
int iDocNo = int.Parse(docNo);
int iVersion = int.Parse(versionNo);
doc = imanagedatabase.GetDocument(iDocNo, iVersion);
openNRTDocument(ref doc, isReadOnly);
imanagedatabase.Session.Logout();
myDMS.Close();
}
catch (Exception Ex)
{
imanagedatabase.Session.Logout();
throw Ex;
}
finally
{
imanagedatabase = null;
myDMS = null;
}
}
public void openNRTDocument(ref IManDocument nrtDocument, Boolean isReadonly)
{
OpenCmd cmd = new OpenCmd();
ContextItems objContextItems = new ContextItems();
objContextItems.Add("NRTDMS", myDMS);
objContextItems.Add("SelectedNRTDocuments", new[] { (NRTDocument)nrtDocument.LatestVersion });
objContextItems.Add("IManExt.OpenCmd.Integration", false);
objContextItems.Add("IManExt.OpenCmd.NoCmdUI", true);
cmd.Initialize(objContextItems);
cmd.Update();
cmd.Execute();
}
}
}
Due to the nature of the error, I am presuming it is a configuration issue rather than a code error although I could be completely wrong as I am very new to programming.
I have found out that w3wp.exe is an IIS worker process created by the app pool but other than that I have no idea what the numeric code represents. Any help or advice is greatly appreciated.
The error is being raised by the OpenCmd instance because it is most likely trying to access resources such as local registry settings. It's not possible to do that in a web application, unless you host your code in a proprietary technology like ActiveX (which is specific to Internet Explorer)
Actually, it is not appropriate for you to use OpenCmd here. Those type of commands (iManage "ICommand" implementations) are intended to be used in regular Windows applications that have either the iManage FileSite or DeskSite client installed. These commands are all part of the so-called Extensibility COM libraries (iManExt.dll, iManExt2.dll, etc) and should not be used in web applications, or at least used with caution as they may inappropriately attempt to access the registry, as you've discovered, or perhaps even display input Win32 dialogs.
For a web app you should instead just limit yourself to the low-level iManage COM library (IManage.dll). This is in fact what iManage themselves do with their own WorkSite Web application
Probably what you should do is replace your openNRTDocument method with something like this:
// create a temporary file on your web server..
var filePath = Path.GetTempFileName();
// fetch a copy of the iManage document and save to the temporary file location
doc.GetCopy(filePath, imGetCopyOptions.imNativeFormat);
In an MVC web application you would then just return a FileContentResult, something like this:
// read entire document as a byte array
var docContent = File.ReadAllBytes(filePath);
// delete temporary copy of file
File.Delete(filePath);
// return byte stream to web client
return File(stream, MediaTypeNames.Application.Octet, fileName);
In a Web Forms application you could do something like this:
// set content disposition as appropriate - here example is for Word DOCX files
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
// write file to HTTP content output stream
Response.WriteFile(filePath);
Response.End();
I am developing a REST web service using WCF and C# (VS 2010). I want to develop an operation like this:
doSomethingWithAFile(String filePath)
so it would be invoked like this:
GET http://my.web.service/endpoint?filePath={filePath}
filePath is a file path in the client (not in the server). So, when invoked, that operation has to send the file pointed by the path to the server so that the server can do some operations with the data contained in the file.
How can I achieve this?
EDIT: As stated in the comment I made, I would set a shared folder in the client, so I send the path and the server reads the file in the folder.
On your server, you will have to have a service with a method that accepts a string input, which you call with the file path from the client application.
You then read/copy/whichever the file from that location, on your server via normal file IO methods.
An example of how to do this you can find below.
The definition of ServerPleaseFetchThisFile naturally depends on what kind of webservice this would be, WCF or IIS web service or self made web service.
public bool ServerPleaseFetchThisFile(string targetPath)
{
// targetPath should enter from the client in format of \\Hostname\Path\to\the\file.txt
return DoSomethingWithAFile(targetPath);
}
private bool DoSomethingWithAFile(string targetFile)
{
bool success = false;
if (string.IsNullOrWhiteSpace(targetFile))
{
throw new ArgumentNullException("targetFile", "The supplied target file is not a valid input.");
}
if (!File.Exists(targetFile))
{
throw new ArgumentNullException("targetFile", "The supplied target file is not a valid file location.");
}
try
{
using (FileStream targetStream = new FileStream(targetFile, FileMode.Open, FileAccess.Read))
{
// Do something with targetStream
success = true;
}
}
catch (SecurityException se)
{
throw new Exception("Security Exception!", se);
// Do something due to indicate Security Exception to the file
// success = false;
}
catch (UnauthorizedAccessException uae)
{
throw new Exception("Unathorized Access!", uae);
// Do something due to indicate Unauthorized Access to the file
// success = false;
}
return success;
}
I am attempting to download a file from another IIS site on my local machine. I have my main website that is trying to download from another public site that contains a few files that the user will be able to download.
[HttpGet]
public ActionResult DownloadMyPrintManagerInstaller()
{
bool success;
try
{
using (var client = new WebClient())
{
client.DownloadFile(new Uri("http://localhost:182//MyPrintInstaller.exe"), "MyPrintManager.exe");
}
success = true;
}
catch (Exception)
{
success = false;
}
return Json(new { Success = success }, JsonRequestBehavior.AllowGet);
}
For some reason, it is attempting to download the file from C:\windows\system32\inetsrv\MyPrintManager.exe? Does anyone know how I can avoid it from pointing to that directory? Do I need to modify my code or my IIS configuration?
My virtual directory for this site is a folder sitting on my C: drive, and the file I actually want to download is in that directory.
No, it's attempting to save the file to C:\windows\system32\inetsrv\MyPrintManager.exe.
That's because C:\windows\system32\inetsrv is the working directory for your process, and you've just given a relative filename.
Specify an absolute filename which says exactly where you want the file to be stored, and it should be fine.
WebClient web = new WebClient();
string url = "http://.../FILENAME.jpg";
web.DownloadFile(new Uri(url), "C:/FILENAME.jpg");
I wrote a program to download files from a website by using WebClient.DownloadFile().
public static void downWeb()
{
WebClient myWebClient = new WebClient();
path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (add() == 1)
{
Console.WriteLine("Response is " + add());
Console.WriteLine("Downloading File = " + dynFileName + "....");
myWebClient.DownloadFile(fullAddress, (path + dynFileName));
}
}
public static int add()
{
string url = fullAddress;
WebRequest webRequest = WebRequest.Create(url);
WebResponse webResponse;
try
{
webResponse = webRequest.GetResponse();
}
catch
{
return 0;
}
return 1;
}
downWeb() is a function to be called in the Main() function.
add() is a function that tests the availability of the file on server. If response is positive, it returns value "1".
fullAddress = address from where the files has to downloaded. It's changing every time before calling this function in a loop present in Main().
When I start my application, I ask the user to:
1) Enter URL to be downloaded i.e. www.1234.com\samplefiles\pg-1.pdf
2) Number of pages to be downloaded (By changing the above filename no. in a loop as rest of the url is same on server)
Now my problem is when I am downloading files, first file downloads PERFECTLY, but the second download is never finished. It says "REQUEST TIMED OUT", and my application closes.
I don't know what's happening here.
How can this be solved?
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse.aspx
You must call the Close method to close the stream and release the connection. Failure to do so may cause your application to run out of connections.
Your problem likely is related to the fact that you do not dispose of your connections. You should make sure that you don't leak them.