0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C#自アセンブリ(.exe)の親ディレクト下にディレクトリを作る方法。

Last updated at Posted at 2018-02-05

以下はアセンブリファイルのあるディレクトリの親ディkレクト下に,"Log"ディレクトを作成します。

DirectoryInfo dirInfo = Directory.GetParent(Assembly.GetEntryAssembly().Location);
DirectotyInfo dirBase = Directoty.GetParent(dirInfo.FullName);
DirectoryInfo dirTarget = dirBase.CreateSubdirectory("Log");
string fileName = string.Format("Data{0}.Log", DateTime.Now.ToString("yyyyMMddTHHmmss"));
string fullPath = Path.Combine(dirTarget.FullName, fileName); 
Utility.cs
using System;
using System.IO;
using System.Reflection;

namespace EUtility
{
    public class Utility
    {
        /// <summary>
        /// アセンブリ(.exe)のある親ディレクト下に指定した名前のディレクトを作成してそのパスを返します。
        /// たとえば bin\foo.exeから呼び出すとbinと兄弟レベルのディレクトを作成します。
        /// </summary>
        /// <param name="subDirName">サブディレクト</param>
        /// <returns></returns>
        public static string GetAssemblyParentSubPath(string subDirName)
        {
            if (subDirName == null)
                throw new ArgumentNullException("subDirName");

            DirectoryInfo dirInfo = Directory.GetParent(Assembly.GetEntryAssembly().Location);
            DirectoryInfo dirBase = dirInfo.Parent;
            string target = Path.Combine(dirBase.FullName, subDirName);

            if ( ! Directory.Exists(target))
            {
                Directory.CreateDirectory(target);
            }
            return target;
        }
        /// <summary>
        /// アセンブリ(.exe)のある親ディレクト下に指定した名前のディレクトを作成し,
        /// filenameを付加してfullpathを返します。
        /// </summary>
        /// <param name="subDirName">サブディレクト名</param>
        /// <param name="filename">ファイル名</param>
        /// <returns></returns>

        public static string GetAssemblyParentSubFile(string subDirName, string filename)
        {
            if (subDirName == null)
                throw new ArgumentNullException("subDirName");

            if (filename == null)
                throw new ArgumentNullException("filename");

            return Path.Combine(GetAssemblyParentSubPath(subDirName), filename);
        }
    }
}



0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?