Monday, April 20, 2009

A VB.NET console app to backup your blog(s)

If you want a small program that you can run periodically to backup your blogger blogs, you can use the following source code with the Google GData .NET Library.

See Sorting photo data from Google's Picasa API for another example of using the GData .NET library.

Code highlights
  • You need to supply your email address and password at service.Credentials
  • You need to specify the backup folder (Dim folder as String =)
  • The file is written as an XML file in
    • a sub-folder based on each blog's title
    • uses a unique filename based on the date and time
Imports Google.GData.Client
Imports System.Xml
Imports System.Text.RegularExpressions
Imports System.Net
Imports System.IO
Module Module1
    Dim exp As New Regex("[^a-zA-Z0-9]")
    Dim service As New Service("blogger", "BloggerSampleApp")
    Sub Main()
        service.Credentials = New GDataCredentials("<emailaddress>", "<password>")
        Dim query As New FeedQuery
        query.Uri = New Uri("")
            Dim bloggerFeed As AtomFeed = service.Query(query)
            While bloggerFeed.Entries.Count > 0
                For Each entry As AtomEntry In bloggerFeed.Entries
                If bloggerFeed.NextChunk = Nothing Then
                    Exit While
                End If
                query.Uri = New Uri(bloggerFeed.NextChunk)
                bloggerFeed = service.Query(query)
            End While
        Catch ex As Exception
        End Try
    End Sub
    Sub exportBlog(ByVal blog As AtomEntry)
        Dim title As String = blog.Title.Text
        Dim folder As String = "M:\WWW\Blogs\" + title
        Catch ex As Exception
        End Try
        Dim filename As String = folder + "\" + exp.Replace(Now.ToString("s"), "") + ".xml"
        Console.WriteLine(vbTab + filename)
        Dim o As New FileStream(filename, FileMode.Create)
        Dim blogId As String = ""
        Dim ss() As String = blog.SelfUri.Content.Split("/")
        For i As Integer = 0 To ss.Count - 1
            If ss(i).ToLower.Equals("blogs") Then
                blogId = ss(i + 1)
            End If
        Dim url As String = "" + blogId + "/archive"
        Dim str As IO.Stream = service.Query(New Uri(url))
        Dim b(50000) As Byte
        While True
            Dim len As Integer = str.Read(b, 0, 50000)
            o.Write(b, 0, len)
            If len < 1 Then
                Exit While
            End If
        End While
    End Sub
End Module

No comments: