Использование каталога файлов в качестве параметра - PullRequest
0 голосов
/ 11 июня 2018

РЕДАКТИРОВАНИЕ: Извинения за ошибки - я понимаю, не очень ясно.

Я создал библиотеку классов, которую я хочу заполнить несколькими методами / функциями.Я работаю над одним из этих методов, однако я изо всех сил пытаюсь использовать метод, используя пользовательский каталог.

См. Код метода в библиотеке классов:

public class SharpFuntions
    {
        public static void CreateFile(string location){
            string path = location;
                try
                   {
                    // Delete the file if it exists.
                    if (File.Exists(path))
                        {
                    File.Delete(path);
                        }
                    // Create the file.
                    File.Create(path);
                        {
                        }
                    }
                catch (Exception ex)
                        {
                            Console.WriteLine(ex.ToString());
                        }
        }           
    }

Теперь, когда я пытаюсь вызвать эту функцию и использовать каталог, она не проходит.См. Ниже:

static void Main(string[] args)
{  
    SharpFuntions.CreateFile(@"C:\User\Text.txt");
}

Я не уверен, возможно ли вышеизложенное.Я просто хочу иметь возможность вызывать функцию и, возможно, иметь возможность вставлять новый каталог / имя файла каждый раз, когда я его использую.

Так что ниже работает, что я знаю, однако я не хочу жестко кодировать каталог / имя файла

public class SharpFuntions
    {
        public static void CreateFile(){
            string path = @"c:\temp\MyTest2.txt";
                try
                   {
                    // Delete the file if it exists.
                    if (File.Exists(path))
                        {
                    File.Delete(path);
                        }
                    // Create the file.
                    File.Create(path)
                        {
                        }
                    }
                catch (Exception ex)
                        {
                            Console.WriteLine(ex.ToString());
                        }
        }    

Ответы [ 2 ]

0 голосов
/ 11 июня 2018

вы можете попробовать использовать FileInfo

 public static void CreateFile(string location)
            {
                var fileInfo = new FileInfo(location);
                try
                {
                    // Delete the file if it exists.
                    if (fileInfo.Exists)
                    {
                        fileInfo.Delete();
                    }
                    // Create the file and directory.
              if (!Directory.Exists(fileInfo.DirectoryName))
                    Directory.CreateDirectory(fileInfo.DirectoryName);


                    fileInfo.Create();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
0 голосов
/ 11 июня 2018

File.Create Method (String)

Создает или перезаписывает файл по указанному пути.

path Тип:System.String

Путь и имя создаваемого файла.

Метод File.Delete (String)

Удаляет указанный файл.

Метод File.Exists (String)

Определяет, существует ли указанный файл.

SharpFuntions.CreateFile(@"C:\User");

...

// path is not a file name, it will never work

File.Create(path);

Ни один из показанных вами методов не использует путь, они используют имя файла.Вам нужно изменить это

Лучший пример

public static void CreateFile(string fileName)
{
    try
    {
       // Delete the file if it exists.
       if (File.Exists(fileName))
       {
          // Note that no lock is put on the
          // file and the possibility exists
          // that another process could do
          // something with it between
          // the calls to Exists and Delete.
          File.Delete(fileName);
       }

       // create empty file
       using (File.Create(fileName));

       // Create the file.
       //using (FileStream fs = File.Create(fileName))
       //{
       //   Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
       //    Add some information to the file.
       //   fs.Write(info, 0, info.Length);
       //}

       // Open the stream and read it back.
       //using (StreamReader sr = File.OpenText(fileName))
       //{
       //   string s = "";
       //   while ((s = sr.ReadLine()) != null)
       //   {
       //      Console.WriteLine(s);
       //   }
       //}
    }   
    catch (Exception ex)
    {
        // log
        // message
        // output to a console, or something
        Console.WriteLine(ex.ToString());
    }
}

использование

string fileName = @"c:\temp\MyTest.txt";

CreateFile(fileName);

Обновление

Я обновил код, чтобы создать пустой файл, если вы этого хотите

...