Nowadays, we're facing a bigger chance to download a file from URL since more documents are electronically delivered by internet. In this article, I'll introduce how to download a Word document from URL programmatically using Spire.Doc in C#, VB.NET.
Spire.Doc does not provide a method to download a Word file directly from URL. However, you can download the file from URL into a MemoryStream and then use Spire.Doc to load the document from MemoryStream and save as a new Word document to local folder.
Code Snippet:
Step 1: Initialize a new Word document.
Document doc = new Document();
Step 2: Initialize a new instance of WebClient class.
WebClient webClient = new WebClient();
Step 3: Call WebClient.DownloadData(string address) method to load the data from URL. Save the data to a MemoryStream, then call Document.LoadFromStream() method to load the Word document from MemoryStream.
using (MemoryStream ms = new MemoryStream(webClient.DownloadData("http://www.e-iceblue.com/images/test.docx"))) { doc.LoadFromStream(ms,FileFormat.Docx); }
Step 4: Save the file.
doc.SaveToFile("result.docx",FileFormat.Docx);
Run the program, the targeted file will be downloaded and saved as a new Word file in Bin folder.
Full Code:
using Spire.Doc; using System.IO; using System.Net; namespace DownloadfromURL { class Program { static void Main(string[] args) { Document doc = new Document(); WebClient webClient = new WebClient(); using (MemoryStream ms = new MemoryStream(webClient.DownloadData("http://www.e-iceblue.com/images/test.docx"))) { doc.LoadFromStream(ms, FileFormat.Docx); } doc.SaveToFile("result.docx", FileFormat.Docx); } } }
Imports Spire.Doc Imports System.IO Imports System.Net Namespace DownloadfromURL Class Program Private Shared Sub Main(args As String()) Dim doc As New Document() Dim webClient As New WebClient() Using ms As New MemoryStream(webClient.DownloadData("http://www.e-iceblue.com/images/test.docx")) doc.LoadFromStream(ms, FileFormat.Docx) End Using doc.SaveToFile("result.docx", FileFormat.Docx) End Sub End Class End Namespace