I am having a strange issue with my ftp class its not sending the file to the server my main code is creating the file ok locally however its not saving it on the server no error is created just completes as if it has transfered it I checked permissions of the user and it is fine.
public void Send(string file)
{
try
{
// read the contents of the file.
byte[] contents = ReadFileContents(file);
var requestUriString = string.Concat(_remoteHost, "/", Path.GetFileName(file));
var request = (FtpWebRequest)WebRequest.Create(requestUriString);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(_remoteUser, _remotePassword);
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(contents, 0, contents.Length);
requestStream.Close();
}
}catch(Exception ex)
{
Helper.Log(ex.Message);
}
}
And I checked the request uri is fine. After futher checking .net is reporitng
I have asked the web company to check there server cause it should be there for them even though I cannot see it in filezilla some reason?
This is how my uri looks like
ftp://ftp.mydomain.biz/2018-05-09-14-11.csv
Edit2
The file should go to the root.
Related
I have a valid download url for a file located in google firebase storage and I'm trying to download the file into my application written which is in c# via a HTTP Get request. However, the request fails with the error "WebException: The remote server returned an error: (400) Bad Request." I would really appreciate it if you could point me towards what I'm doing wrong. Thank you in advance for your help! -- Here is reference to the google firebase documentation https://firebase.google.com/docs/storage/web/download-files
Below is the code I am using to download the file:
private void downloadFrame()
{
//Extract
try
{
//construct HTTP get request
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(**link address**);
httpRequest.Method = "GET";
httpRequest.ContentType = "text/xml; encoding='utf-8'";
//send the http request and get the http response from webserver
HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
Stream httpResponseStream = httpResponse.GetResponseStream();
// Define buffer and buffer size
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int bytesRead = 0;
// Read from response and write to file
FileStream fileStream = File.Create("frame.pcm");
while ((bytesRead = httpResponseStream.Read(buffer, 0, bufferSize)) != 0)
{
fileStream.Write(buffer, 0, bytesRead);
} // end while
}
catch (WebException we)
{
Debug.Log(we.Response.ToString());
}
}
I realize this is a very old question, but I hit it when I had the same issue and it took me quite a while to find an answer.
The download link I had from Firebase was for a PDF file and contained an escaped "/" character as "%2F". This was being changed back into a "/" on the fly, causing the error.
The answer I required was to alter this behaviour by adding an entry to the web.config file as described here: https://stackoverflow.com/a/12170132
I could then use a simple WebClient to download the file like this:
string targetFileName = #"C:\Temp\Target.pdf"
using (WebClient client = new WebClient())
{
Uri downloadURI = new Uri(<Firebase download URL>);
client.DownloadFile(downloadURI, targetFileName);
}
Note: By default, Cloud Storage buckets require Firebase
Authentication to download files. You can change your Firebase
Security Rules for Cloud Storage to allow unauthenticated access
https://firebase.google.com/docs/storage/web/download-files
Change this and try again.
I'm trying to upload files from ASP.Net to Sharepoint (In-order to preserve TimeStamp I'm using this way)
The following is my code
protected void UploadFileToSharePoint(string UploadedFilePath, string SharePointPath)
{
WebResponse response = null;
try
{
string SUrl = "http://MysharepointPath/Folder";
//WebRequest request = WebRequest.Create(SharePointPath);
WebRequest request = WebRequest.Create(SUrl);
request.Credentials = new NetworkCredential(username,password );
//request.Method = "PUT";
request.Method = "POST";
FileStream fStream = File.OpenRead(UploadedFilePath);
string fileName = fStream.Name.Substring(3);
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
request.ContentLength = 0;
//Custom code
using (WebClient uploader = new WebClient())
{
try
{
uploader.UploadFile(new Uri(SUrl), UploadedFilePath);
}
catch (Exception ex)
{
}
}
response = request.GetResponse();
}
}
When i try to run the code in debug mode it throws exception
"remote server returned an error 401 unauthorized"
What do you mean by '(In-order to preserve TimeStamp I'm using this way)'? the timestamp on the uploaded document in SharePoint's going to be the date the document was added to the SharePoint document library
The error 401 (Unauthorized), indicates that the client must first authenticate itself, so can you use Fiddler to validate if you're authenticating in the SharePoint server?
Are you using SharePoint Online or OnPremises?.
There are a few samples in codeplex for what you're trying to accomplish, please review this link for more information...
http://spfileupload.codeplex.com/SourceControl/latest#Get-SPScripts.Copy-FilesToSP.ps1
I found a lot of question about (401) Unauthorized error, but none of them explained to me how to diagnose the issue.
I created a new MVC ASP.net app to learn how to upload a file to a sharepoint folder. As of right now, I can't seem to be able to copy a file from
C:\testfolder\file.txt to
C:\testfolder\UploadedFiles
Here is the method that I made where I send in the source file path and the target folder:
//Flag to indicate whether file was uploaded successfuly or not
bool isUploaded = true;
try
{
// Create a PUT Web request to upload the file.
WebRequest request = WebRequest.Create(targetDocumentLibraryPath);
//Set credentials of the current security context
request.PreAuthenticate = true;
request.UseDefaultCredentials = true;
ICredentials credentials = new NetworkCredential( "Username", "password", "Domain"); //I used my username and password here
request.Credentials = credentials;
//request.Credentials = CredentialCache.DefaultCredentials;
request.Method = "PUT";
// Create buffer to transfer file
byte[] fileBuffer = new byte[1024];
// Write the contents of the local file to the request stream.
using (Stream stream = request.GetRequestStream())
{
//Load the content from local file to stream
using (FileStream fsWorkbook = File.Open(sourceFilePath, FileMode.Open, FileAccess.Read))
{
//Get the start point
int startBuffer = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length);
for (int i = startBuffer; i > 0; i = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length))
{
stream.Write(fileBuffer, 0, i);
}
}
}
// Perform the PUT request
WebResponse response = request.GetResponse();
//Close response
response.Close();
}
catch (Exception ex)
{
//Set the flag to indiacte failure in uploading
isUploaded = false; //The remote server returned an error: (401) Unauthorized.
}
//Return the final upload status
return isUploaded;
}
I tried the following:
Changing the permission of the folders to be able to write/read from them for all users.
Use other folder locations (SharePoint, local drive, network drive) to upload the file to.
Any idea on how to get this problem to work? Any prospective on how to debug the problem is also appreciated.
Update: It is probably being my account is set as the app pool account in IIS. I am still not sure what the issue is.
This wouldn't be something like the proxy settings would it?
Do you need to add the default proxy setting to your
WebRequest
Also do you need to add
<system.net>
<defaultProxy useDefaultCredentials="true" />
</system.net>
To your web config?
This may help.
How should I set the default proxy to use default credentials?
I decided to try another approach and use httpposted file and .saveAs() described here
I've just written a simple FTP console app to upload files on a local server to a remote FTP site. Everything seems to be working fine until it comes to actually transferring the file. For some reason instead of uploading the file to the specified FTP site it stores the entire file locally with no in the Debug folder with no file type and named the same as the ip of the FTP site. I'm thinking that this has something to do with Visual Studio's debugging. Can anybody give me some guidance on this?
Here is the code I'm using to attempt to upload each file in a string array to the FTP site.
private static void Upload(string ftpServer, string userName, string password, string filename)
{
using (var client = new WebClient())
{
client.Credentials = new NetworkCredential(userName, password);
client.UploadFile(ftpServer, "STOR", filename);
}
}
Use this method instead of that one,it worked for me.
//Directory sands for Remote Server Directory ,it must create if dir not exist
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://serverIP/directory/file");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential ("username","password");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader("testfile.txt");
byte [] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
source- http://msdn.microsoft.com/en-us/library/ms229715.aspx
Try this way instead: http://msdn.microsoft.com/en-us/library/ms229715.aspx
I'm trying to download a file from a url. I try two approachs but it isn't working with external files.
I think it's happening because I have internet over proxy. I can download internal network files (images, mp3, mp4, whatever...) but when I try to download something in external network it gives me timeout or 404 Not Found.
1st approach: System.Net.WebResponse, System.IO.FileStream
try
{
var credentials = new NetworkCredential("myNetworkUserName", "myNetworkPassword", "myNetworkDomain");
var proxy = WebProxy.GetDefaultProxy(); //new WebProxy("myNetworkProxy") <-- I TRY BOOTH WAYS
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://farm1.static.flickr.com/83/263570357_e1b9792c7a.jpg"); //External image link
proxy.Credentials = credentials;
request.Proxy = proxy;
responseExternalImage = request.GetResponse();//explode here ex=""Unable to connect to the remote server""
string fileName = GetFileName(response.ResponseUri.OriginalString);
Stream stream = response.GetResponseStream();
using (BinaryReader br = new BinaryReader(stream))
{
content = br.ReadBytes(50000000);//perto de 50Mb
br.Close();
}
response.Close();
FileStream fs = new FileStream(pathToSaveFile + "\\" + fileName, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
try
{
bw.Write(content);
}
finally
{
fs.Close();
bw.Close();
}
}
catch (Exception ex)
{
}
The exception caught at GetResponse() says: "Unable to connect to the remote server", ""A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 77.238.160.184:80""
2nd approach: System.Net.WebClient, DownloadFile
try
{
var credentials = new NetworkCredential("xpta264", ConfigurationManager.AppSettings["Xpta264Password"], "ptsi");
var proxy = WebProxy.GetDefaultProxy();
proxy.Credentials = credentials;
// Create a new WebClient instance.
using (WebClient myWebClient = new WebClient())
{
myWebClient.Proxy = proxy;
// Download the Web resource and save it into the current filesystem folder.
myWebClient.DownloadFile("http://farm1.static.flickr.com/83/263570357_e1b9792c7a.jpg", pathToSaveFile + "\\testImage.jpg");
}
}
catch (Exception e)
{
}
The exception was caught at DownloadFile method and gives me the same error.
Hope someone can help me.
Sorry for my English
WebProxy.GetDefaultProxy() is obsolete and doesn't handle all cases. From the docs:
Note: This API is now obsolete.
The GetDefaultProxy method does not pick up any dynamic settings that
are generated from scripts run by Internet Explorer, from automatic
configuration entries, or from DHCP or DNS lookups.
Applications should use the WebRequest.DefaultWebProxy property and
the WebRequest.GetSystemWebProxy method instead of the GetDefaultProxy
method.
A better approach is to try to request a url and see if a proxy was used. I use this code in my own production system and it seems to work pretty well. Once you find the proxy, you can cache the address somewhere:
WebProxy proxy = null;
Uri testUri = new Uri("http://www.example.com/"); // replace with REAL url
Uri proxyEndpoint = WebRequest.GetSystemWebProxy().GetProxy(testUri);
if (!testUri.Equals(proxyEndpoint))
proxy = new WebProxy(proxyEndPoint.ToString());
You can also just try calling WebRequest.GetSystemWebProxy() and see if that gives you the proxy, but I remember having problems with that which is why I went the request route above. YMMV.