0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

cscの作法 その24 WebRequest

0
Last updated at Posted at 2020-01-03

概要

cscの作法、調べてみた。
練習問題やってみた。

練習問題

pdfダウンローダーを作れ。

サンプルコード

using System;
using System.Windows.Forms;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;

class form1: Form {
	TextBox bo1;
	form1() {
		Text = "download";
		ClientSize = new Size(580, 200);
		bo1 = new TextBox();
		bo1.Location = new Point(50, 50);
		bo1.Width = 500;
		bo1.Text = "https://www.jitec.ipa.go.jp/1_04hanni_sukiru/mondai_kaitou_2015h27_1/2015h27h_fe_am_qs.pdf";
		Controls.AddRange(new Control[] {
			bo1
		});
		Button btn1 = new Button();
		btn1.Location = new Point(50, 90);
		btn1.Text = "test";
		btn1.Click += btn1_Click;
		Controls.AddRange(new Control[] {
			btn1
		});
	}
	void btn1_Click(object sender, System.EventArgs e) {
		string url = bo1.Text;
		string filename = DateTime.Now.ToString("HH-mm-ss") + ".pdf";
		WebRequest req = WebRequest.Create(url);
		WebResponse res = req.GetResponse();
		Stream st = res.GetResponseStream();
		byte[] buf = new byte[32768];
		MemoryStream ms = new MemoryStream();
		while (true)
		{
			int read = st.Read(buf, 0, buf.Length);
			if (read > 0)
			{
				ms.Write(buf, 0, read);
			}
			else
			{
				break;
			}
		}
		FileStream fs = new FileStream(filename, FileMode.Create);
		byte[] wbuf = new byte[ms.Length];
		ms.Seek(0, SeekOrigin.Begin);
		ms.Read(wbuf, 0, wbuf.Length);
		fs.Write(wbuf, 0, wbuf.Length);
		fs.Close();
		MessageBox.Show(filename);
	}
	[STAThread]
	public static void Main() {
		Application.Run(new form1());
	}
}





以上。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?