how to save the webpage using c#? - c#

How to save the webpage using c#? I need to open a dialog asking for the path to save the file.
Any help?

Create a file chooser like explained on this blog .
And then a web client
WebClient Client = new WebClient ();
Client.DownloadFile("pagename", " saveasname");

Here's another way:
private string DownlodHTMLPage(Uri url)
{
WebResponse response = null;
Stream stream = null;
StreamReader sr = null;
try
{
HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(url);
//sometimes it doesn't work if user agent is not set
hwr.UserAgent = "Opera/9.80 (Windows NT 5.1; U; pl) Presto/2.2.15 Version/10.10";
response = hwr.GetResponse();
stream = response.GetResponseStream();
//check if content type of page is text/xxx. you can add statement for XHTML files
if (!response.ContentType.ToLower().StartsWith("text/"))
{
return null;
}
string buffer = "", line;
//get the stream reader
sr = new StreamReader(stream);
//download HTML to buffer
while ((line = sr.ReadLine()) != null)
{
buffer += line + "\r\n"; //line with new line markers
}
return buffer;
}
catch (WebException e)
{
System.Console.WriteLine("Can't download from " + url + " 'casue " + e);
return null;
}
catch (IOException e)
{
System.Console.WriteLine("Can't download from " + url + " 'cause " + e);
return null;
}
finally
{
if (sr != null)
sr.Close();
if (stream != null)
stream.Close();
if (response != null)
response.Close();
}
}
Edit
To answer the question in comment of Ranjana. Method above just download a web page and returns it as a string. You save it later using e.g StreamWriter:
StreamWriter writer = new StreamWriter(PATH_TO_FILE, false, Encoding.UTF8);
writer.Write(DownlodHTMLPage(uri));
Path to file you can get using SaveFileDialog, e.g.:
SaveFileDialog dialog = new SaveFileDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
string file = dialog.FileName;
//rest of the code comes here
}
I hope that this is what you were asking for.

Related

Download GitHub files in directories

I have this function in my script:
private void DownloadFile(string file, string location)
{
var githubToken = "[token]";
var request = (HttpWebRequest)WebRequest.Create("https://api.github.com/repos/[owner]/[repo]/contents/" + file);
request.Headers.Add(HttpRequestHeader.Authorization, string.Concat("token ", githubToken));
request.Accept = "application/vnd.github.v3.raw";
request.UserAgent = "useragent";
try
{
using (var response = request.GetResponse())
{
var encoding = System.Text.ASCIIEncoding.UTF8;
using (var reader = new StreamReader(response.GetResponseStream(), encoding))
{
/*using (StreamWriter sw = File.CreateText(location))
{
sw.WriteLine(reader.ReadToEnd());
sw.Close();
}*/
using (FileStream fs = File.Create(location))
{
byte[] info = new UTF8Encoding(true).GetBytes(reader.ReadToEnd());
fs.Write(info, 0, info.Length);
}
reader.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show("ERROR: " + ex + "\n " + file);
}
}
So downloading a single file in the root directory like repo/text.txt, this works great! But when I want to download the file in files/file1.rar, that doesn't work. It gives me an 403 or 404. Can somebody explain why this is, and how to download files from a directory (the repository is private, therefore the large chunk of code)

how to download file from ftp in a local windows application gridview cell content click

i have displayed some files from ftp in my local windows application data gridview. i put a button in datagridview,when i click that download button which is shown in datagridveiw ftp files donwload please help me
1) how to download files from the following data gridview , these file get from ftp server
i have the follwing download method.
public bool DownloadFile(string url, string fileName, string userName, string password, string destinationPath)
{
String directoryPath = string.Empty;
Stream responseStream = null;
FileStream writeStream = null;
MemoryStream memoryStream = null;
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(#url + "/" + fileName.Trim());
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
request.Timeout = -1;
request.UsePassive = true;
request.Credentials = new NetworkCredential(userName, password);
memoryStream = new MemoryStream();
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
responseStream = response.GetResponseStream();
responseStream.CopyTo(memoryStream);
responseStream.Close();
responseStream.Dispose();
string filePath = destinationPath;
//filePath = filePath + "//" + "Reciepts//";
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
if (!File.Exists(#filePath + "/" + fileName))
{
writeStream = new FileStream(#filePath + "/" + fileName.TrimEnd().TrimStart(), FileMode.Create);
memoryStream.WriteTo(writeStream);
memoryStream.Close();
memoryStream.Dispose();
writeStream.Close();
return true;
}
}
}
catch (Exception ex)
{
return false;
}
return true;
}
e.g
Check this:
void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
//if click is on new row or header row
if( e.RowIndex == dataGridView1.NewRowIndex || e.RowIndex < 0)
return;
//Handle Button Click
//dataGridView1.Columns[YourColumnIndex] works too
if( e.ColumnIndex == dataGridView1.Columns["YourColumnName"].Index)
{
//Do the stuff for button click
//for example DownloadFile(url, dataGridView1.Rows[e.RowIndex].Cells["YourFileNameColumn"].Value.ToString(), username, password, destinationPath)
MessageBox.Show("Button Clicked");
}
}
Remember you can get value of a cell by its column index and by its column name, for example:
dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString()
dataGridView1.Rows[e.RowIndex].Cells["DataGridViewTextBoxColumn1"].Value.ToString()

Issue in Download file from google drive api in .net

I want to download document from Google Drive.for that I am using Google Drive API. I am very new to Google Drive API so can any one tell me how to download document from google Drive ?
I have try this option from here but I am getting exception on line
HttpWebRequest request = (HttpWebRequest)WebRequest.Create( new Uri(file.DownloadUrl.ToString()));
authenticator.ApplyAuthenticationToRequest(request); HttpWebResponse response = (HttpWebResponse)request.GetResponse();
like
The underlying connection was closed: An unexpected error occurred on
a send.
Unable to read data from the transport connection: An existing
connection was forcibly closed by the remote host.
I thing this problem occur because of scope. please tell me how to set scope in application
pls not I am creating desktop application in c# .net
can any one help me ?
This code works for me:
var stream = service.HttpClient.GetStreamAsync(file.DownloadUrl);
var result = stream.Result;
using (var fileStream = System.IO.File.Create(filePathToSaveFileOnDisk))
{
result.CopyTo(fileStream);
}
Have a look at the code example here: https://developers.google.com/drive/v2/reference/files/get
I am using this code to download files from google drive
public void Download(object sender, DoWorkEventArgs e)
{
List<File> driveFiles = Google.Apis.Util.Utilities.RetrieveAllFiles(service);
int fileCount = driveFiles.Count;
int i = 0;
IAuthenticator authenticator = new CloudManager().CreateAuthentication();
foreach (var driveFile in driveFiles.Where(driveFile => driveFile.MimeType != "video/mp4"))
{
LabelFileProcess.Dispatcher.BeginInvoke(DispatcherPriority.Background,
(Action) (() => LabelFileProcess.Content = driveFile.Title));
string title = driveFile.Title;
LabelFileProcess.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
(Action) (() => LabelFileProcess.Content = title));
if (string.IsNullOrEmpty(driveFile.Title))
{
MessageBox.Show(#"File's title is emplty");
continue;
}
if (driveFile.MimeType != "application/vnd.google-apps.folder")
{
Stream stream = Utilities.DownloadFile(authenticator, driveFile);
if (stream != null)
Utilities.SaveFile(stream, driveFile.Title);
}
else
Directory.CreateDirectory("D:\\GdriveFiles\\" + driveFile.Title);
}
Main Download processing methods
public void Download(object sender, DoWorkEventArgs e)
{
List<File> driveFiles = Google.Apis.Util.Utilities.RetrieveAllFiles(service);
int fileCount = driveFiles.Count;
int i = 0;
IAuthenticator authenticator = new CloudManager().CreateAuthentication();
foreach (var driveFile in driveFiles.Where(driveFile => driveFile.MimeType != "video/mp4"))
{
LabelFileProcess.Dispatcher.BeginInvoke(DispatcherPriority.Background,
(Action) (() => LabelFileProcess.Content = driveFile.Title));
string title = driveFile.Title;
LabelFileProcess.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
(Action) (() => LabelFileProcess.Content = title));
if (string.IsNullOrEmpty(driveFile.Title))
{
MessageBox.Show(#"File's title is emplty");
continue;
}
if (driveFile.MimeType != "application/vnd.google-apps.folder")
{
Stream stream = DownloadFile(authenticator, driveFile);
if (stream != null)
SaveFile(stream, driveFile.Title);
}
else
Directory.CreateDirectory("D:\\GdriveFiles\\" + driveFile.Title);
}
public static System.IO.Stream DownloadFile(IAuthenticator authenticator, File file)
{
if (!string.IsNullOrEmpty(file.DownloadUrl))
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(file.DownloadUrl));
authenticator.ApplyAuthenticationToRequest(request);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
return response.StatusCode == HttpStatusCode.OK ? response.GetResponseStream() : null;
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show("Exception occures " + e.Message);
}
else
System.Windows.Forms.MessageBox.Show(#"File doesn't have any content on Drive, Title: "+file.Title);
return null;
}
public static void SaveFile(System.IO.Stream stream, String title)
{
StreamReader streamReader = new StreamReader(stream);
//System.Windows.MessageBox.Show(streamReader.ToString());
if (stream == null)
System.Windows.MessageBox.Show("Error Occured during download");
else
{
FileStream fileStream = System.IO.File.Create("D:\\GdriveFiles\\" + title);
char[] charArray = new char[100];
int count;// = streamReader.Read(arrayByte, 0, 100);
//streamReader.Read(arrayByte, 0, (int)stream.Length);
//fileStream.Write(arrayByte,0,arrayByte.Length);
string incomingMessage = "";
do
{
try
{
count = streamReader.Read(charArray, 0, 100);
incomingMessage += new string(charArray, 0, count);
byte[] byteArray = new byte[charArray.Length];
//byteArray = System.Text.Encoding.Unicode.GetBytes(charArray);
byteArray = System.Text.Encoding.ASCII.GetBytes(charArray);
fileStream.Write(byteArray, 0, count);
}
catch (ArgumentException ex)
{
MessageBox.Show(#"File ended, Exception:" + ex.Message);
break;
}
catch (Exception e)
{
MessageBox.Show("Exception occure" + e.Message);
break;
}
} while (count > 0);
fileStream.Close();
//MessageBox.Show("File Contains are " + incomingMessage);
}
}

Uploading an image using C# and WebRequest?

Here is the working code in Python (using cURL):
#!/usr/bin/python
import pycurl
c = pycurl.Curl()
values = [
("key", "YOUR_API_KEY"),
("image", (c.FORM_FILE, "file.png"))]
# OR: ("image", "http://example.com/example.jpg"))]
# OR: ("image", "BASE64_ENCODED_STRING"))]
c.setopt(c.URL, "http://imgur.com/api/upload.xml")
c.setopt(c.HTTPPOST, values)
c.perform()
c.close()
Here's what I have in C#:
public void UploadImage()
{
//I think this line is doing something wrong.
//byte[] x = File.ReadAllBytes(#"C:\Users\Sergio\documents\visual studio 2010\Projects\WpfApplication1\WpfApplication1\Test\hotness2.jpg");
//If I do it like this, using a direct URL everything works fine.
string parameters = #"key=1b9189df79bf3f8dff2125c22834210903&image=http://static.reddit.com/reddit.com.header.png"; //Convert.ToBase64String(x);
WebRequest webRequest = WebRequest.Create(new Uri("http://imgur.com/api/upload"));
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(parameters);
Stream os = null;
try
{ // send the Post
webRequest.ContentLength = bytes.Length; //Count bytes to send
os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length); //Send it
}
catch (WebException ex)
{
MessageBox.Show(ex.Message, "HttpPost: Request error");
}
finally
{
if (os != null)
{
os.Close();
}
}
try
{ // get the response
WebResponse webResponse = webRequest.GetResponse();
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
MessageBox.Show(sr.ReadToEnd().Trim());
}
catch (WebException ex)
{
MessageBox.Show(ex.Message, "HttpPost: Response error");
}
}
Now, the things I noticed is that when I changed my API key in the parameters string to "239231" or whatever number, the response I got was: "Invalid API key." So I think something must be working right.
I placed my correct API key and now I get a different response: "Invalid image format. Try uploading a JPEG image."
The service I'm using accepts almost every image format, so I am 100% certain the error is in the way I'm sending the file. Can anyone shed some light?
EDIT!!!
It turns out when I upload a JPG image I get that gray box thing. If I upload a big jpg image I don't get anything. For example: http://i.imgur.com/gFsUY.jpg
When I upload PNG's, the image uploaded doesn't even show.
I'm certain the issue is the encoding. What can I do?
EDIT 2!!!
Now I'm 100% certain that the problem lies in the first line of the method. The File.ReadAllBytes() must be doing something wrong. If I upload a URL file, every works peachy: http://imgur.com/sVH61.png
I wonder what encoding I should use. :S
Try this:
string file = #"C:\Users\Sergio\documents\visual studio 2010\Projects\WpfApplication1\WpfApplication1\Test\Avatar.png";
string parameters = #"key=1df918979bf3f8dff2125c22834210903&image=" +
Convert.ToBase64String(File.ReadAllBytes(file));
You should correctly form a multipart POST request. See an example here: Upload files with HTTPWebrequest (multipart/form-data)
Read image posted by in API
public IHttpActionResult UpdatePhysicianImage(HttpRequestMessage request)
{
try
{
var form = HttpContext.Current.Request.Form;
var model = JsonConvert.DeserializeObject<UserPic>(form["json"].ToString());
bool istoken = _appdevice.GettokenID(model.DeviceId);
if (!istoken)
{
statuscode = 0;
message = ErrorMessage.TockenNotvalid;
goto invalidtoken;
}
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
var docfiles = new List<string>();
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
// var filePath = uploadPath + postedFile.FileName;
// string fileUrl = Utility.AbsolutePath("~/Data/User/" + model.UserId.ToString());
string fileUrl = Utility.AbsolutePath("~/" + Utility.UserDataFolder(model.UserId, "Document"));
if (!Directory.Exists(fileUrl))
{
Directory.CreateDirectory(fileUrl);
Directory.CreateDirectory(fileUrl + "\\" + "Document");
Directory.CreateDirectory(fileUrl + "\\" + "License");
Directory.CreateDirectory(fileUrl + "\\" + "Profile");
}
string imageUrl = postedFile.FileName;
string naviPath = Utility.ProfileImagePath(model.UserId, imageUrl);
var path = Utility.AbsolutePath("~/" + naviPath);
postedFile.SaveAs(path);
docfiles.Add(path);
if (model.RoleId == 2)
{
var doctorEntity = _doctorProfile.GetNameVideoChat(model.UserId);
doctorEntity.ProfileImagePath = naviPath;
_doctorProfile.UpdateDoctorUpdProfile(doctorEntity);
}
else
{
var patientEntity = _PatientProfile.GetPatientByUserProfileId(model.UserId);
patientEntity.TumbImagePath = naviPath;
_PatientProfile.UpdatePatient(patientEntity);
}
}
result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
}
else
{
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
catch (Exception e)
{
statuscode = 0;
message = "Error" + e.Message;
}
invalidtoken:
return Json(modeldata.GetData(statuscode, message));
}
Try changing :-
"application/x-www-form-urlencoded"
to
"multipart/form-data"
Try adding the content-type for the jpg into your multipart boundary.
See this uRL for examples (at the end)
http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2
Shot in the dark, but maybe create an instance of Image, save the file to a Stream and use that to read the bytes into an array then upload it.
As in:
Image i = System.Drawing.Image.FromFile("wut.jpg");
Stream stm = new Stream();
System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
System.Drawing.Imaging.EncoderParameters paramz = new System.Drawing.Imaging.EncoderParameters(1);
myEncoderParameter = new EncoderParameter(myEncoder, 100L);
paramz.Param[0] = myEncoderParameter;
i.Save(stm, System.Drawing.Imaging.ImageFormat.Jpeg, paramz);
/* I'm lazy: code for reading Stream into byte[] here */

How do I programatically download a file from a sharepoint site?

I have a sharepoint site that has an excel spreadsheet that I need to download on a schedulad basis
Is this possible?
Yes it is possible to download the file from sharepoint.
Once you have the url for the document, it can be downloaded using HttpWebRequest and HttpWebResponse.
attaching a sample code
DownLoadDocument(string strURL, string strFileName)
{
HttpWebRequest request;
HttpWebResponse response = null;
request = (HttpWebRequest)WebRequest.Create(strURL);
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.Timeout = 10000;
request.AllowWriteStreamBuffering = false;
response = (HttpWebResponse)request.GetResponse();
Stream s = response.GetResponseStream();
// Write to disk
if (!Directory.Exists(myDownLoads))
{
Directory.CreateDirectory(myDownLoads);
}
string aFilePath = myDownLoads + "\\" + strFileName;
FileStream fs = new FileStream(aFilePath, FileMode.Create);
byte[] read = new byte[256];
int count = s.Read(read, 0, read.Length);
while (count > 0)
{
fs.Write(read, 0, count);
count = s.Read(read, 0, read.Length);
}
// Close everything
fs.Close();
s.Close();
response.Close();
}
You can also use the GetItem API of Copy service to download a file.
string aFileUrl = mySiteUrl + strFileName;
Copy aCopyService = new Copy();
aCopyService.UseDefaultCredentials = true;
byte[] aFileContents = null;
FieldInformation[] aFieldInfo;
aCopyService.GetItem(aFileUrl, out aFieldInfo, out aFileContents);
The file can be retrieved as a byte array.
You can also do this:
try
{
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential("username", "password", "DOMAIN");
client.DownloadFile(http_path, path);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
The link the to document in Sharepoint should be a static URL. Use that URL in whatever solution you have to grab the file on your schedule.
Why not just use wget.exe <url>. You can put that line in a batch file and run that through windows scheduler.

Categories

Resources