1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 // (c) 2008-2011 Moz (@syo68k)
4 // (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
5 // (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 // (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 // (c) 2011 Egtra (@egtra) <http://dev.activebasic.com/egtra/>
8 // (c) 2011 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
9 // All rights reserved.
11 // This file is part of OpenTween.
13 // This program is free software; you can redistribute it and/or modify it
14 // under the terms of the GNU General public License as published by the Free
15 // Software Foundation; either version 3 of the License, or (at your option)
18 // This program is distributed in the hope that it will be useful, but
19 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
20 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
23 // You should have received a copy of the GNU General public License along
24 // with this program. if not, see <http://www.gnu.org/licenses/>, or write to
25 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
26 // Boston, MA 02110-1301, USA.
31 using System.Collections.Generic;
35 using System.Windows.Forms;
37 using System.Globalization;
38 using System.Security.Cryptography;
40 using System.Drawing.Imaging;
41 using System.Collections;
42 using System.Security.Principal;
43 using System.Runtime.Serialization.Json;
44 using System.Reflection;
45 using System.Diagnostics;
46 using System.Text.RegularExpressions;
48 using System.Net.Http;
49 using System.Net.NetworkInformation;
50 using System.Runtime.InteropServices;
52 using OpenTween.Models;
53 using OpenTween.Setting;
57 public static class MyCommon
59 private static readonly object LockObj = new object();
60 public static bool _endingFlag; //終了フラグ
61 public static string settingPath;
72 public enum NameBalloonEnum
79 public enum DispTitleEnum
91 public enum LogUnitEnum
98 public enum UploadFileType
105 public enum UrlConverter
119 public enum HITRESULT
128 public enum HttpTimeOut
135 //Backgroundworkerへ処理種別を通知するための引数用enum
136 public enum WORKERTYPE
140 DirectMessegeRcv, //受信DM取得
141 DirectMessegeSnt, //送信DM取得
142 PostMessage, //発言POST
145 Follower, //Followerリスト取得
151 UserStream, //UserStream
152 UserTimeline, //UserTimeline
153 BlockIds, //Blocking/ids
154 Configuration, //Twitter Configuration読み込み
155 NoRetweetIds, //RT非表示ユーザー取得
157 ErrorState, //エラー表示のみで後処理終了(認証エラー時など)
160 public static class DEFAULTTAB
162 public const string RECENT = "Recent";
163 public const string REPLY = "Reply";
164 public const string DM = "Direct";
165 public const string FAV = "Favorites";
166 public static readonly string MUTE = Properties.Resources.MuteTabName;
168 //private string dummy;
170 //private object ReferenceEquals()
172 // return new object();
174 //private object Equals()
176 // return new object();
180 public static readonly object? Block = null;
181 public static bool TraceFlag = false;
184 public static bool DebugBuild = true;
186 public static bool DebugBuild = false;
189 public enum ACCOUNT_STATE
195 public enum REPLY_ICONSTATE
203 public enum EVENTTYPE
210 ListMemberRemoved = 16,
218 ListUserSubscribed = 4096,
219 ListUserUnsubscribed = 8192,
220 ListDestroyed = 16384,
223 QuotedTweet = 131072,
226 All = (None | Favorite | Unfavorite | Follow | ListMemberAdded | ListMemberRemoved |
227 Block | Unblock | UserUpdate | Deleted | ListCreated | ListUpdated | Unfollow |
228 ListUserSubscribed | ListUserUnsubscribed | ListDestroyed |
229 Mute | Unmute | QuotedTweet | Retweet),
232 public static _Assembly EntryAssembly { get; internal set; }
233 public static string FileVersion { get; internal set; }
237 var assembly = Assembly.GetExecutingAssembly();
238 MyCommon.EntryAssembly = assembly;
240 var fileVersionAttribute = (AssemblyFileVersionAttribute)assembly
241 .GetCustomAttributes(typeof(AssemblyFileVersionAttribute)).First();
242 MyCommon.FileVersion = fileVersionAttribute.Version;
245 public static string GetErrorLogPath()
246 => Path.Combine(Path.GetDirectoryName(MyCommon.EntryAssembly.Location), "ErrorLogs");
248 public static void TraceOut(WebApiException ex)
250 var message = ExceptionOutMessage(ex);
252 if (ex.ResponseText != null)
253 message += Environment.NewLine + "------- Response Data -------" + Environment.NewLine + ex.ResponseText;
255 TraceOut(TraceFlag, message);
258 public static void TraceOut(Exception ex, string Message)
260 var buf = ExceptionOutMessage(ex);
261 TraceOut(TraceFlag, Message + Environment.NewLine + buf);
264 public static void TraceOut(string Message)
265 => TraceOut(TraceFlag, Message);
267 public static void TraceOut(bool OutputFlag, string Message)
271 if (!OutputFlag) return;
273 var logPath = MyCommon.GetErrorLogPath();
274 if (!Directory.Exists(logPath))
275 Directory.CreateDirectory(logPath);
277 var now = DateTimeUtc.Now;
278 var fileName = $"{ApplicationSettings.AssemblyName}Trace-{now.ToLocalTime():yyyyMMdd-HHmmss}.log";
279 fileName = Path.Combine(logPath, fileName);
281 using var writer = new StreamWriter(fileName);
283 writer.WriteLine("**** TraceOut: {0} ****", now.ToLocalTimeString());
284 writer.WriteLine(Properties.Resources.TraceOutText1, ApplicationSettings.FeedbackEmailAddress);
285 writer.WriteLine(Properties.Resources.TraceOutText2, ApplicationSettings.FeedbackTwitterName);
287 writer.WriteLine(Properties.Resources.TraceOutText3);
288 writer.WriteLine(Properties.Resources.TraceOutText4, Environment.OSVersion.VersionString);
289 writer.WriteLine(Properties.Resources.TraceOutText5, Environment.Version);
290 writer.WriteLine(Properties.Resources.TraceOutText6, ApplicationSettings.AssemblyName, FileVersion);
291 writer.WriteLine(Message);
297 // 注意:最終的にファイル出力されるエラーログに記録されるため次の情報は書き出さない
299 // Dataプロパティにある終了許可フラグのパースもここで行う
301 public static string ExceptionOutMessage(Exception ex)
303 var IsTerminatePermission = true;
304 return ExceptionOutMessage(ex, ref IsTerminatePermission);
307 public static string ExceptionOutMessage(Exception ex, ref bool IsTerminatePermission)
309 if (ex == null) return "";
311 var buf = new StringBuilder();
313 buf.AppendFormat(Properties.Resources.UnhandledExceptionText8, ex.GetType().FullName, ex.Message);
317 var needHeader = true;
318 foreach (DictionaryEntry dt in ex.Data)
323 buf.AppendLine("-------Extra Information-------");
326 buf.AppendFormat("{0} : {1}", dt.Key, dt.Value);
328 if (dt.Key.Equals("IsTerminatePermission"))
330 IsTerminatePermission = (bool)dt.Value;
335 buf.AppendLine("-----End Extra Information-----");
338 buf.AppendLine(ex.StackTrace);
341 //InnerExceptionが存在する場合書き出す
342 var _ex = ex.InnerException;
346 buf.AppendFormat("-----InnerException[{0}]-----\r\n", nesting);
348 buf.AppendFormat(Properties.Resources.UnhandledExceptionText8, _ex.GetType().FullName, _ex.Message);
350 if (_ex.Data != null)
352 var needHeader = true;
354 foreach (DictionaryEntry dt in _ex.Data)
359 buf.AppendLine("-------Extra Information-------");
362 buf.AppendFormat("{0} : {1}", dt.Key, dt.Value);
363 if (dt.Key.Equals("IsTerminatePermission"))
365 IsTerminatePermission = (bool)dt.Value;
370 buf.AppendLine("-----End Extra Information-----");
373 buf.AppendLine(_ex.StackTrace);
376 _ex = _ex.InnerException;
378 return buf.ToString();
381 public static bool ExceptionOut(Exception ex)
385 var IsTerminatePermission = true;
387 var ident = WindowsIdentity.GetCurrent();
388 var princ = new WindowsPrincipal(ident);
389 var now = DateTimeUtc.Now;
391 var errorReport = string.Join(Environment.NewLine,
392 string.Format(Properties.Resources.UnhandledExceptionText1, now.ToLocalTimeString()),
395 string.Format(Properties.Resources.UnhandledExceptionText11 + princ.IsInRole(WindowsBuiltInRole.Administrator)),
396 string.Format(Properties.Resources.UnhandledExceptionText12 + princ.IsInRole(WindowsBuiltInRole.User)),
399 // OSVersion,AppVersion書き出し
400 string.Format(Properties.Resources.UnhandledExceptionText4),
401 string.Format(Properties.Resources.UnhandledExceptionText5, Environment.OSVersion.VersionString),
402 string.Format(Properties.Resources.UnhandledExceptionText6, Environment.Version),
403 string.Format(Properties.Resources.UnhandledExceptionText7, ApplicationSettings.AssemblyName, FileVersion),
405 ExceptionOutMessage(ex, ref IsTerminatePermission));
407 var logPath = MyCommon.GetErrorLogPath();
408 if (!Directory.Exists(logPath))
409 Directory.CreateDirectory(logPath);
411 var fileName = $"{ApplicationSettings.AssemblyName}-{now.ToLocalTime():yyyyMMdd-HHmmss}.log";
412 using (var writer = new StreamWriter(Path.Combine(logPath, fileName)))
414 writer.Write(errorReport);
417 var settings = SettingManager.Common;
418 var mainForm = Application.OpenForms.OfType<TweenMain>().FirstOrDefault();
421 if (mainForm != null && !mainForm.IsDisposed)
422 report = new ErrorReport(mainForm.TwitterInstance, errorReport);
424 report = new ErrorReport(errorReport);
426 report.AnonymousReport = settings.ErrorReportAnonymous;
428 OpenErrorReportDialog(mainForm, report);
430 // ダイアログ内で設定が変更されていれば保存する
431 if (settings.ErrorReportAnonymous != report.AnonymousReport)
433 settings.ErrorReportAnonymous = report.AnonymousReport;
441 private static void OpenErrorReportDialog(Form? owner, ErrorReport report)
443 if (owner != null && owner.InvokeRequired)
445 owner.Invoke((Action)(() => OpenErrorReportDialog(owner, report)));
449 using var dialog = new SendErrorReportForm();
450 dialog.ErrorReport = report;
451 dialog.ShowDialog(owner);
455 /// URLのドメイン名をPunycode展開します。
457 /// ドメイン名がIDNでない場合はそのまま返します。
458 /// ドメインラベルの区切り文字はFULLSTOP(.、U002E)に置き換えられます。
461 /// <param name="inputUrl">展開対象のURL</param>
462 /// <returns>IDNが含まれていた場合はPunycodeに展開したURLをを返します。Punycode展開時にエラーが発生した場合はnullを返します。</returns>
463 public static string? IDNEncode(string inputUrl)
467 var uriBuilder = new UriBuilder(inputUrl);
469 var idnConverter = new IdnMapping();
470 uriBuilder.Host = idnConverter.GetAscii(uriBuilder.Host);
472 return uriBuilder.Uri.AbsoluteUri;
480 public static string IDNDecode(string inputUrl)
484 var uriBuilder = new UriBuilder(inputUrl);
486 if (uriBuilder.Host != null)
488 var idnConverter = new IdnMapping();
489 uriBuilder.Host = idnConverter.GetUnicode(uriBuilder.Host);
492 return uriBuilder.Uri.AbsoluteUri;
501 /// URL を画面上で人間に読みやすい文字列に変換する(エスケープ解除など)
503 public static string ConvertToReadableUrl(string inputUrl)
507 var outputUrl = inputUrl;
510 outputUrl = MyCommon.IDNDecode(outputUrl);
512 // URL内で特殊な意味を持つ記号は元の文字に変換されることを避けるために二重エスケープする
513 // 参考: Firefoxの losslessDecodeURI() 関数
514 // http://hg.mozilla.org/mozilla-central/annotate/FIREFOX_AURORA_27_BASE/browser/base/content/browser.js#l2128
515 outputUrl = Regex.Replace(outputUrl, @"%(2[3456BCF]|3[ABDF]|40)", @"%25$1", RegexOptions.IgnoreCase);
518 outputUrl = Uri.UnescapeDataString(outputUrl);
522 catch (UriFormatException)
528 public static void MoveArrayItem(int[] values, int idx_fr, int idx_to)
530 var moved_value = values[idx_fr];
531 var num_moved = Math.Abs(idx_fr - idx_to);
535 Array.Copy(values, idx_to, values,
536 idx_to + 1, num_moved);
540 Array.Copy(values, idx_fr + 1, values,
544 values[idx_to] = moved_value;
547 public static string EncryptString(string str)
549 if (string.IsNullOrEmpty(str)) return "";
552 var bytesIn = Encoding.UTF8.GetBytes(str);
554 //DESCryptoServiceProviderオブジェクトの作成
555 using var des = new DESCryptoServiceProvider();
559 var bytesKey = Encoding.UTF8.GetBytes("_tween_encrypt_key_");
561 des.Key = ResizeBytesArray(bytesKey, des.Key.Length);
562 des.IV = ResizeBytesArray(bytesKey, des.IV.Length);
564 MemoryStream? msOut = null;
565 ICryptoTransform? desdecrypt = null;
569 //暗号化されたデータを書き出すためのMemoryStream
570 msOut = new MemoryStream();
573 desdecrypt = des.CreateEncryptor();
575 //書き込むためのCryptoStreamの作成
576 using var cryptStream = new CryptoStream(msOut, desdecrypt, CryptoStreamMode.Write);
578 //Disposeが重複して呼ばれないようにする
584 cryptStream.Write(bytesIn, 0, bytesIn.Length);
585 cryptStream.FlushFinalBlock();
587 var bytesOut = msTmp.ToArray();
589 //Base64で文字列に変更して結果を返す
590 return Convert.ToBase64String(bytesOut);
595 desdecrypt?.Dispose();
599 public static string DecryptString(string str)
601 if (string.IsNullOrEmpty(str)) return "";
603 //DESCryptoServiceProviderオブジェクトの作成
604 using var des = new DESCryptoServiceProvider();
608 var bytesKey = Encoding.UTF8.GetBytes("_tween_encrypt_key_");
610 des.Key = ResizeBytesArray(bytesKey, des.Key.Length);
611 des.IV = ResizeBytesArray(bytesKey, des.IV.Length);
613 //Base64で文字列をバイト配列に戻す
614 var bytesIn = Convert.FromBase64String(str);
616 MemoryStream? msIn = null;
617 ICryptoTransform? desdecrypt = null;
618 CryptoStream? cryptStreem = null;
622 //暗号化されたデータを読み込むためのMemoryStream
623 msIn = new MemoryStream(bytesIn);
625 desdecrypt = des.CreateDecryptor();
626 //読み込むためのCryptoStreamの作成
627 cryptStreem = new CryptoStream(msIn, desdecrypt, CryptoStreamMode.Read);
629 //Disposeが重複して呼ばれないようにする
633 //復号化されたデータを取得するためのStreamReader
634 using var srOut = new StreamReader(cryptStreem, Encoding.UTF8);
636 //Disposeが重複して呼ばれないようにする
640 var result = srOut.ReadToEnd();
647 desdecrypt?.Dispose();
648 cryptStreem?.Dispose();
652 public static byte[] ResizeBytesArray(byte[] bytes,
655 var newBytes = new byte[newSize];
656 if (bytes.Length <= newSize)
658 foreach (var i in Enumerable.Range(0, bytes.Length))
660 newBytes[i] = bytes[i];
666 foreach (var i in Enumerable.Range(0, bytes.Length))
668 newBytes[pos] = unchecked((byte)(newBytes[pos] ^ bytes[i]));
670 if (pos >= newBytes.Length)
680 public enum TabUsageType
684 Mentions = 2, //Unique
685 DirectMessage = 4, //Unique
686 Favorites = 8, //Unique
688 LocalQuery = 32, //Pin(no save/no save query/distribute/no update(normal update))
689 Profile = 64, //Pin(save/no distribute/manual update)
690 PublicSearch = 128, //Pin(save/no distribute/auto update)
695 SearchResults = 4096,
701 public static TwitterApiStatus TwitterApiInfo = new TwitterApiStatus();
703 public static bool IsAnimatedGif(string filename)
708 img = Image.FromFile(filename);
709 if (img == null) return false;
710 if (img.RawFormat.Guid == ImageFormat.Gif.Guid)
712 var fd = new FrameDimension(img.FrameDimensionsList[0]);
713 var fd_count = img.GetFrameCount(fd);
735 public static DateTimeUtc DateTimeParse(string input)
737 var formats = new[] {
738 "ddd MMM dd HH:mm:ss zzzz yyyy",
739 "ddd, d MMM yyyy HH:mm:ss zzzz",
742 if (DateTimeUtc.TryParseExact(input, formats, DateTimeFormatInfo.InvariantInfo, out var result))
745 TraceOut("Parse Error(DateTimeFormat) : " + input);
747 return DateTimeUtc.Now;
750 public static T CreateDataFromJson<T>(string content)
752 var buf = Encoding.Unicode.GetBytes(content);
753 using var stream = new MemoryStream(buf);
754 var settings = new DataContractJsonSerializerSettings
756 UseSimpleDictionaryFormat = true,
758 return (T)((new DataContractJsonSerializer(typeof(T), settings)).ReadObject(stream));
761 public static bool IsNetworkAvailable()
765 return NetworkInterface.GetIsNetworkAvailable();
773 public static bool IsValidEmail(string strIn)
775 // Return true if strIn is in valid e-mail format.
776 return Regex.IsMatch(strIn,
777 @"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))" +
778 @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$");
782 /// 指定された修飾キーが押されている状態かを取得します。
784 /// <param name="keys">状態を調べるキー</param>
785 /// <returns><paramref name="keys"/> で指定された修飾キーがすべて押されている状態であれば true。それ以外であれば false。</returns>
786 public static bool IsKeyDown(params Keys[] keys)
787 => MyCommon._IsKeyDown(Control.ModifierKeys, keys);
789 internal static bool _IsKeyDown(Keys modifierKeys, Keys[] targetKeys)
791 foreach (var key in targetKeys)
793 if ((modifierKeys & key) != key)
802 /// アプリケーションのアセンブリ名を取得します。
805 /// VB.NETの<code>My.Application.Info.AssemblyName</code>と(ほぼ)同じ動作をします。
807 /// <returns>アプリケーションのアセンブリ名</returns>
808 public static string GetAssemblyName()
809 => MyCommon.EntryAssembly.GetName().Name;
812 /// 文字列中に含まれる %AppName% をアプリケーション名に置換する
814 /// <param name="orig">対象となる文字列</param>
815 /// <returns>置換後の文字列</returns>
816 public static string ReplaceAppName(string orig)
817 => MyCommon.ReplaceAppName(orig, ApplicationSettings.ApplicationName);
820 /// 文字列中に含まれる %AppName% をアプリケーション名に置換する
822 /// <param name="orig">対象となる文字列</param>
823 /// <param name="appname">アプリケーション名</param>
824 /// <returns>置換後の文字列</returns>
825 public static string ReplaceAppName(string orig, string appname)
826 => orig.Replace("%AppName%", appname);
829 /// 表示用のバージョン番号の文字列を生成する
832 /// バージョン1.0.0.1のように末尾が0でない(=開発版)の場合は「1.0.1-beta1」が出力される
837 public static string GetReadableVersion(string? versionStr = null)
839 var version = Version.Parse(versionStr ?? MyCommon.FileVersion);
841 return GetReadableVersion(version);
845 /// 表示用のバージョン番号の文字列を生成する
848 /// バージョン1.0.0.1のように末尾が0でない(=開発版)の場合は「1.0.1-dev」のように出力される
853 public static string GetReadableVersion(Version version)
855 var versionNum = new[] { version.Major, version.Minor, version.Build, version.Revision };
857 if (versionNum[3] == 0)
859 return string.Format("{0}.{1}.{2}", versionNum[0], versionNum[1], versionNum[2]);
863 versionNum[2] = versionNum[2] + 1;
865 if (versionNum[3] == 1)
866 return string.Format("{0}.{1}.{2}-dev", versionNum[0], versionNum[1], versionNum[2]);
868 return string.Format("{0}.{1}.{2}-dev+build.{3}", versionNum[0], versionNum[1], versionNum[2], versionNum[3]);
872 public const string TwitterUrl = "https://twitter.com/";
874 public static string GetStatusUrl(PostClass post)
876 if (post.RetweetedId == null)
877 return GetStatusUrl(post.ScreenName, post.StatusId);
879 return GetStatusUrl(post.ScreenName, post.RetweetedId.Value);
882 public static string GetStatusUrl(string screenName, long statusId)
883 => TwitterUrl + screenName + "/status/" + statusId;
886 /// 指定された IDictionary を元にクエリ文字列を生成します
888 /// <param name="param">生成するクエリの key-value コレクション</param>
889 public static string BuildQueryString(IEnumerable<KeyValuePair<string, string>> param)
895 .Where(x => x.Value != null)
896 .Select(x => EscapeQueryString(x.Key) + '=' + EscapeQueryString(x.Value));
898 return string.Join("&", query);
901 // .NET 4.5+: Reserved characters のうち、Uriクラスによってエスケープ強制解除されてしまうものも最初から Unreserved として扱う
902 private static readonly HashSet<char> UnreservedChars =
903 new HashSet<char>("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~!'()*:");
906 /// 2バイト文字も考慮したクエリ用エンコード
908 /// <param name="stringToEncode">エンコードする文字列</param>
909 /// <returns>エンコード結果文字列</returns>
910 public static string EscapeQueryString(string stringToEncode)
912 var sb = new StringBuilder(stringToEncode.Length * 2);
914 foreach (var b in Encoding.UTF8.GetBytes(stringToEncode))
916 if (UnreservedChars.Contains((char)b))
919 sb.AppendFormat("%{0:X2}", b);
922 return sb.ToString();
926 /// 指定された範囲の整数を昇順に列挙します
929 /// start, start + 1, start + 2, ..., end の範囲の数列を生成します
931 /// <param name="from">数列の先頭の値 (最小値)</param>
932 /// <param name="to">数列の末尾の値 (最大値)</param>
933 /// <returns>整数を列挙する IEnumerable インスタンス</returns>
934 public static IEnumerable<int> CountUp(int from, int to)
937 return Enumerable.Empty<int>();
939 return Enumerable.Range(from, to - from + 1);
943 /// 指定された範囲の整数を降順に列挙します
946 /// start, start - 1, start - 2, ..., end の範囲の数列を生成します
948 /// <param name="from">数列の先頭の値 (最大値)</param>
949 /// <param name="to">数列の末尾の値 (最小値)</param>
950 /// <returns>整数を列挙する IEnumerable インスタンス</returns>
951 public static IEnumerable<int> CountDown(int from, int to)
953 for (var i = from; i >= to; i--)
957 public static IEnumerable<int> CircularCountUp(int length, int startIndex)
960 throw new ArgumentOutOfRangeException(nameof(length));
961 if (startIndex < 0 || startIndex >= length)
962 throw new ArgumentOutOfRangeException(nameof(startIndex));
965 var indices = MyCommon.CountUp(startIndex, length - 1);
967 // 先頭 ... (startIndex - 1)
969 indices = indices.Concat(MyCommon.CountUp(0, startIndex - 1));
974 public static IEnumerable<int> CircularCountDown(int length, int startIndex)
977 throw new ArgumentOutOfRangeException(nameof(length));
978 if (startIndex < 0 || startIndex >= length)
979 throw new ArgumentOutOfRangeException(nameof(startIndex));
982 var indices = MyCommon.CountDown(startIndex, 0);
984 // 末尾 ... (startIndex + 1)
985 if (startIndex != length - 1)
986 indices = indices.Concat(MyCommon.CountDown(length - 1, startIndex + 1));
992 /// 2バイト文字も考慮したUrlエンコード
994 /// <param name="stringToEncode">エンコードする文字列</param>
995 /// <returns>エンコード結果文字列</returns>
996 public static string UrlEncode(string stringToEncode)
998 const string UnreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
999 var sb = new StringBuilder();
1000 var bytes = Encoding.UTF8.GetBytes(stringToEncode);
1002 foreach (var b in bytes)
1004 if (UnreservedChars.IndexOf((char)b) != -1)
1007 sb.AppendFormat("%{0:X2}", b);
1009 return sb.ToString();