Windows Live Writer をテキストエディタから開く

Metro アプリストアへの登録記念ということで(単に、登録をだけで、アプリの公開はまだですが)、
Windows Live Writer を外部から操作する tips ということで。

準備としては、以下にあるように

c# – Windows Live Writer Automation – Stack Overflow
http://stackoverflow.com/questions/8490977/windows-live-writer-automation

regsvr32 WindowsLiveWriter.Application.dll

をレジストリ登録。こうしないと、IWindowsLiveWriterApplication2 へのキャストでエラーになります。何故かわからんけど、そういうものみたい。

これで作ったのが以下なコードです。

[img 20120927_01]

20120927_01

の形式で画像を貼りつけることができます。

namespace LiveWriterPost
{
	class Program
	{
		static void Main(string[] args)
		{
			if (args.Length == 0)
			{
				Console.WriteLine("LiveWriterPost [path]");
				return;
			}
			string path = args[0];
			var lw = new LiveWriter();
			lw.NewPost(path);
		}
	}

	public class LiveWriter
	{
		public void NewPost(string path)
		{
			// ファイルコードは UTF-8 で
			var sr = File.OpenText(path);
			// 最初の行はタイトル
			string title = sr.ReadLine();
			// 残りは本文
			string html = sr.ReadToEnd();
			NewPost( title, html );

		}
		public void NewPost( string title, string body )
		{
			string imgdir = @"file://D:\work\blog\image\";

			body = Regex.Replace( body, @"\r\n\[img ([^]]+)\]", "\r\n\<img src='"+imgdir+"'$1.jpg" />");
			// 先頭行を削除
			body = Regex.Replace(body, "^\r\n
", "");
			// 改行を変更
			body = Regex.Replace( body, "\r\n", "
\r\n" );

			var _app = new WindowsLiveWriterApplication();
			var app = (IWindowsLiveWriterApplication2)_app;
			app.BlogThisHtml(title, body );
		}
	}
}

ここのコードの部分は、wordpress 上で [/code] を使って書き直しています。なので、要検討。
あと、リンクの自動設定のところも。

カテゴリー: C# パーマリンク