スキップしてメイン コンテンツに移動

投稿

ラベル(C#)が付いた投稿を表示しています

C#でExcelファイルの読み書き

C#でExcelファイルを読み書きするためには、まず以下の2つの準備が必要です。 Microsoft Office (Excel)のインストール Visual Studioから「参照の追加」=> 「COM」タブからMicrosoft Excel 11 Object Libraryを追加(COMのバージョン部分は、インストールしたOfficeのバージョンに依存します) サンプルコード 以下は、実際にExcelファイルを開いて、Cellへの読み書き、sheetの追加を行うサンプルコードです。 using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Office.Interop.Excel; namespace Example { class ExcelExample { private static void RunExcelExample() { Excel.Workbook book = null; Excel.Application excel = null; try { excel = new Excel.Application(); book = excel.Workbooks.Open(@"c:\test.xls", Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,

C#からOutlookを操作

「メールを受信したときに実行するプログラム」と「メールボックス内のフォルダ情報やinbox内にあるメールを表示する」サンプルコードです。 using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Office.Interop.Outlook; namespace OutlookExample { public class OutlookExample { public static void RunOutlookExample() { ApplicationClass appClass = new ApplicationClass(); appClass.NewMail += new ApplicationEvents_10_NewMailEventHandler(outLookApp_NewMailEx); PrintInbox(appClass); } private static void outLookApp_NewMailEx(string EntryIDCollection) { // do something nice when mail is coming } public static void PrintInbox(ApplicationClass o) { // get items in my inbox (using MAPI) NameSpace outlookNS = o.GetNamespace("MAPI"); MAPIFolder inboxFolder = outlookNS.GetDefaultFolder(OlDefaultFolders.olFolderInbox); foreach (MA

HTMLのMETAタグから文字エンコードを取得するコード

ExtractEncodingメソッドでRegexを使ってMETAタグからcharsetの部分を取り出しています。 Readメソッドでは、まず与えられたpathにあるhtmlファイルからExtractEncodingメソッドを使って適切な文字エンコードを取得します。その後取得した文字コードで読み取ったhtmlを変換しています。 using System; using System.Text; using System.Text.RegularExpressions; using System.IO; namespace Utility { public static class EncodingUtils { private static readonly Regex r = new Regex( @"<META\s+http-equiv\s*=\s*Content-Type\s+content=\s*""[^""]*\s+charset\s*=\s*(?<charset>[^""\s]*).*""\s*>", RegexOptions.IgnoreCase | RegexOptions.Compiled); public static string ExtractEncoding(string html) { string result = null; lock (r) { Match m = r.Match(html); if (m.Success) { result = m.Groups["charset"].Value; } } return result; }

ThreadPoolクラスのサンプル

ThreadPoolクラスのサンプルです。C#のソースコードを以下に示します。もっと有益な情報を載せないといけませんね。 using System; using System.Threading; namespace Test { public static class ThreadPoolTest { public static void RunThread() { ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadMethod), "A"); Console.ReadLine(); } private static void ThreadMethod(object state) { for (int i = 0; i < 10; i++) { System.Console.WriteLine(state+":"+i); Thread.Sleep(1000); } } } }

XmlTextReaderの使い方

備忘録としてSystem.Xml.XmlTextReaderのサンプルを載せておきます。 public static void ReadXMLSample(string path) { for (XmlReader textReader = new XmlTextReader(path); textReader.Read(); textReader.MoveToElement()) { Console.WriteLine("==================="); Console.WriteLine("Name:" + textReader.Name); Console.WriteLine("Base URI:" + textReader.BaseURI); Console.WriteLine("Local Name:" + textReader.LocalName); Console.WriteLine("Attribute Count:" + textReader.AttributeCount); Console.WriteLine("Depth:" + textReader.Depth); Console.WriteLine("Node Type:" + textReader.NodeType); } }

XmlTextWriterの使い方

備忘録としてSystem.Xml.XmlTextWriterのサンプルを載せておきます。 pathにxmlファイルを作成して保存するC#のプログラムです。 public static void CreateXMLSample(string path) { XmlTextWriter writer = new XmlTextWriter(path, Encoding.Default); writer.WriteStartDocument(true); writer.WriteStartElement("root"); for (int i = 0; i < 3; i++) { writer.WriteStartElement("element"); writer.WriteStartAttribute("path"); writer.WriteValue(@"c:\temp\test.txt"); writer.WriteEndAttribute(); for (int j = 0; j < 3; j++) { writer.WriteStartElement("attr"); writer.WriteStartAttribute("type"); writer.WriteValue("integer"); writer.WriteEndAttribute(); writer.WriteStartAttribute("value"); writer.WriteValue(j); writer.WriteEndAttribute(); writer.WriteEndElement(); } writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteEndDocument(); writer.Close(); }

C#: ファイルパスから絶対URIを返すコード

ファイルパスから絶対URIを返すコードです。(特に相対ファイルパスで便利かも知れません。) public static string GetAbsoluteUri(string filepath){ FileInfo fileInfo = new FileInfo(filePath); Uri uri = new Uri(fileInfo.FullName); return uri.AbsoluteUri; } ちなみにコードの色づけには google-code-prettify を使わせて頂きました。さすがGoogle! 使い方は以下のリンクが参考になります。 Learning Log Book: Bloggerでシンタックス・ハイライト

Microsoft Outlookの.msgファイルをC#で読みこむ方法

.NetライブラリのMicrosoft.Office.Interio.Outlookを使う ディスクなどに保存された.msgファイルを読み込むことは難しいのではないかと思います。 未検証です。 CodeProjectで公開されているライブラリを使う このページ で公開されているプロジェクトファイルを使えばできそうです。こういうものをさくっと作れるのはうらやましいですね。 この記事は書き途中です。よりよい方法が見つかり次第更新します!

C#: SaveFileDialogの使用サンプル

SaveFileDialogの基本的な使い方を以下に示します。他の種類のダイアログでも基本的な使い方は同じです。 SaveFileDialog dialog = new SaveFileDialog(); dialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; dialog.FilterIndex = 2; dialog.RestoreDirectory = true; if (dialog.ShowDialog() == DialogResult.OK) { MessageBox.Show("Saved!"); }

WebRequestクラスを使ってStringをPostするコード

使用するEncodingはUTF-8を仮定しています。 public static void PostData(string host, int port, string data) { try { Uri requestUri = new Uri(string.Format("http://{0}:{1}/", host, port)); WebRequest request = WebRequest.Create(requestUri); request.Proxy = new WebProxy(); request.Method = "POST"; byte[] postDataBytes = Encoding.UTF8.GetBytes(data); request.ContentLength = postDataBytes.Length; using (Stream stream = request.GetRequestStream()) { stream.Write(postDataBytes, 0, postDataBytes.Length); WebResponse response = request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { string strResp = reader.ReadToEnd(); // Do something... } } } catch (Exception ex) { log.ErrorFormat("Error in {0} method\n{1}", MethodBase.GetCurrentM

C# and .Net Tips

C#でのリフレクション Dynamically load a class and execute a method in .NET Assembly Load Assembly C# / CSharp Tutorial オープンソースの.Netプラットフォーム Mono : Cross Platform + Open Source .Net environment Microsoft C# でのHTML構文解析 Microsoft C# でのHTML構文解析 Flashを.Net環境 で扱うためのヒント CodeZine の このページ が参考になります。 .Net環境で時間を計測する方法 処理時間を正確に計測するには?[2.0のみ、C#、VB] ImageAnimator C#でGIF Animeを再生できるクラス .NetのApp.configファイル アプリケーション構成ファイル(App.config)、 Web構成ファイル(Web.config)にカスタム構成セクションを追加する C#におけるCastとAs演算子を用いた型変換の性能差 Type casting impact over execution performance in C# .Net用のメールライブラリ JMail.NET 解析ツール FxCop :.Netでコンパイルされたdllを解析するためのツールです。 .Net, C# に関する便利なサイト DOBON.NET 連載:改訂版 C#入門 C# Certification, Development, and Training .Net Tips C# ソースコード集 :色々サンプルがありますので、参考になると思います。 C#とVB.NETの入門サイト