0

Problem: I am trying to create a text file from a web service (local host), but on creation it gets the null argument error for path location. Now I am still using 2012 and was under the impression the code I gave would return the path name, but just returns null.

Aim:

  • Create a new file if one doesn't exist.
  • Get the path of the file for future use.

Question: What are the visual studio 2012 C# methods for creating a text file? I find allot of sources but the code doesn't seem to work with 2012.

My Code:

//Create a file name for the  path
string path = System.IO.Path.Combine(CurrentDirectory, "textFile.txt");

//Check if it exist, if not then create the File
//This is the recommended code by Microsoft
if (!System.IO.File.Exists(path))
{
    System.IO.File.Create(path);
}
dee-see
  • 23,668
  • 5
  • 58
  • 91
Cornelis
  • 1,065
  • 8
  • 23
  • 2
    First of all, Visual Studio and C# are not linked, so it is just Visual C# and not visual studio 2012 C#. Second, i seems that CurrentDirectory is null. Can you check this in the debugger or through output messages? – WeSt Sep 15 '14 at 14:24
  • 1
    What isn't working? You have created a file if it doesn't exist, and you have the path for future use.. – Sayse Sep 15 '14 at 14:25
  • 1
    Which row is triggering the exception? – David Mårtensson Sep 15 '14 at 14:28
  • Something you can refer to [Create a txt file if its not exist and if it exist write a line with C#](http://stackoverflow.com/questions/9907682/create-a-txt-file-if-its-not-exist-and-if-it-exist-write-a-line-with-c-sharp) – Izzy Sep 15 '14 at 14:28
  • `string path = System.IO.Path.Combine(Environment.CurrentDirectory, "textFile.txt");` – Dmitry Bychenko Sep 15 '14 at 14:29
  • What is the value of `path`? – rhughes Sep 15 '14 at 14:56

3 Answers3

0

If you are trying to write something on a txt file, these piece of code does. No need to create a file if it is not exist. These code will create a file automatically if it not exists.

public static void LogMessage(string sFilePath, string sMsg)
        {
            using (StreamWriter sw = File.AppendText(sFilePath))
            {
                sw.WriteLine(string.Format(@"{0} : {1}", DateTime.Now.ToLongTimeString(), sMsg));
            }
        }
Ondipuli
  • 468
  • 3
  • 9
0

Are you sure CurrentDirectory value is right? If you want visit current Web Service root dir can use like AppDomain.CurrentDomain.BaseDirectory.

0

Get the file path using Server.Map path

string FolderPath = Server.MapPath("~/App_Data");
string file = Path.Combine(FolderPath, "textFile.txt");

//Check if it exist, if not then create the File
//This is the recommended code by Microsoft
if (!System.IO.File.Exists(file))
{
    System.IO.File.Create(file);
}

Also check if the IIS user have permission to write on that folder (Add permission to the application pool user)

Ahmad Al Sayyed
  • 596
  • 5
  • 13