【解決方法】フォルダーを作成し、その中にファイルを保存する C#


同僚の皆さん、こんにちは。

私はこのプログラミングの初心者で、楽しみと自己学習のためだけにやっています。
ルーチンを実行するたびに aa フォルダーと Excel ファイルを作成していますが、問題なく動作しています。
しかし、この Excel ファイルを自分のフォルダー内に保存する方法が見つかりません。

フォルダーを作成し、その中に Excel ファイルを保存したいと思います。もちろん、フォルダー名は毎回異なります。

何か案は? どうもありがとうございます。

よろしく。

私が試したこと:

C#
Directory.CreateDirectory("c:\\temp\\" + foldername.Text);

sheet.SaveAs("c:\\Temp\\" + excelname.Text + DateTime.Now.ToString("_yyyyMMdd"));

解決策 2

次のようにすることができます 単純 このように:

using System.IO;

namespace WFTemplate_Aug2020
{
    public static class public_static_class_FileExtensions
    {
        public static FileStream NewFile(this string folderpath, string filename, string extension)
        {
           return File.Create($"{folderpath}{filename}{extension}");
        }
    }
}

呼び出しの例:

FileStream fs = @"C:\Users\test_user\Desktop\New Stuff\".NewFile("xray", ".txt");

でも:

0 このコードは、同じ名前とパスを持つ既存のファイルを上書きします

1 このコードは、「許可が拒否された」、またはファイルが存在して読み取り専用になっているなど、ファイル アクセスで発生する可能性のあるエラーをインターセプトしません。

2 ここでは、// ファイル パス セパレータを使用する際に間違いを犯しやすいことをチェックすることはなく、既存の有効なディレクトリ構造名をチェックすることもありません。

ここで考えられるその他の例外を参照してください。 [^]

「実世界のコード」では、これらの問題に対処する必要があります。

ここでの他の回答は、ディレクトリが存在するかどうかを確認する方法を示しています。

解決策 1

もちろん、あなたはそれを使用してそれを行うことができます Directory.CreateDirectory メソッド (System.IO) | Microsoft Docs[^]

サンプル:

C#
public class CreateFileOrFolder
{
    static void Main()
    {
        // Specify a name for your top-level folder.
        string folderName = @"c:\Top-Level Folder";

        // To create a string that specifies the path to a subfolder under your
        // top-level folder, add a name for the subfolder to folderName.
        string pathString = System.IO.Path.Combine(folderName, "SubFolder");

        // You can write out the path name directly instead of using the Combine
        // method. Combine just makes the process easier.
        string pathString2 = @"c:\Top-Level Folder\SubFolder2";

        // You can extend the depth of your path if you want to.
        //pathString = System.IO.Path.Combine(pathString, "SubSubFolder");

        // Create the subfolder. You can verify in File Explorer that you have this
        // structure in the C: drive.
        //    Local Disk (C:)
        //        Top-Level Folder
        //            SubFolder
        System.IO.Directory.CreateDirectory(pathString);

        // Create a file name for the file you want to create.
        string fileName = System.IO.Path.GetRandomFileName();

        // This example uses a random string for the name, but you also can specify a particular name.
        //string fileName = "MyNewFile.xls";

        // Use Combine again to add the file name to the path.
        pathString = System.IO.Path.Combine(pathString, fileName);

        // Verify the path that you have constructed.
        Console.WriteLine("Path to my file: {0}\n", pathString);

        // Check that the file doesn't already exist. If it doesn't exist, create
        // the file and write integers 0 - 99 to it.
        // DANGER: System.IO.File.Create will overwrite the file if it already exists.
        // This could happen even with random file names, although it is unlikely.
        if (!System.IO.File.Exists(pathString))
        {
            using (System.IO.FileStream fs = System.IO.File.Create(pathString))
            {
                for (byte i = 0; i < 100; i++)
                {
                    fs.WriteByte(i);
                }
            }
        }
    }
    // Sample output:
    // Path to my file: c:\Top-Level Folder\SubFolder\ttxvauxe.vv0
}

参照: ファイルまたはフォルダーを作成する方法 – C# プログラミング ガイド | Microsoft Docs[^]

例を試してみてください。 あなたが共有したものはほとんどすべてそこにあります。

解決策 3

こんにちは、

別の同僚が、私のアプリケーションに適した解決策を提案してくれました。以下のコードを参照してください。

C#
string foldername = foldername.Text;
string myDir = @"c:\temp";
string dirPath = Path.Combine(myDir, foldername);
System.IO.Directory.CreateDirectory(dirPath);


//Specific here where the reporter should be saved

sheet.SaveAs(Path.Combine(dirPath, excelname.Text + DateTime.Now.ToString("_yyyyMMdd")));

コメント

タイトルとURLをコピーしました