Argument Null Exception error when trying to create a Text File - c#

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);
}

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)

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));
}
}

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

Related

Read an xml file from non-web project in C# (Visual Studio)

I am trying to read an xml file that is present in one of the projects in my VS solution. Here's my code.
string path = HttpContext.Current.Server.MapPath(#"~\Resources\XmlDocument.xml");
XDocument document = XDocument.Load(path);
This works fine if my xml file is in the web project. But in reality I have my xml file in a different project under the same solution.
I cannot use Server.MapPath as this searches web project. I searched for an answer but did not find any solution that worked for me.
How can I access this xml file? I am trying to access this from a helper method in the same project.
Try this:
string path = HostingEnvironment.ApplicationPhysicalPath + (some path);
public void LoadXML()
{
if (System.IO.File.Exists(path))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<int>));
lock (new object())
{
using (TextReader reader = new StreamReader(path))
{
return (List<int>)(serializer.Deserialize(reader));
}
}
}
}
this is working for me.
Once you get your current directory, why not just navigate up a number of parent directories and then locate your file?
DirectoryInfo info = new DirectoryInfo(Environment.CurrentDirectory);
DirectoryInfo parent = info.Parent.Parent;
string file = Path.Combine(parent.FullName, #"your\path");
Here I use Environment.CurrentDirectory to get where the program is at now, but you can stack as many Parent elements as you need. Then you can combine the path to get to your file in the other project.
EDIT:
Once your application is running all the environment variables and Server.MapPath will give you the location that it is executing from (i.e. the path you are getting now). In light of this it may be easier to create a folder and reference this via it's full path. (C:\Data\myfile.xml)

How to save and load an XML file in AppData?

I've been teaching myself how to code lately because I am bored. I am trying to load an XML file on startup and put the contents of that file into a listbox, then save the contents of the listbox to the file on close. That's exactly what I have now. However I want to be able to load from AppData as well as save back to the AppData folder without having to type the full path. I've tried using "%AppData%/Roaming/MyApp/data.xml" but that does not work and throws a exception.
Here is what I have now:
StreamReader sr = new StreamReader("data.xml");
line = sr.ReadLine();
while (line != null) {
Streamers.Items.Add(line);
line = sr.ReadLine();
}
Streamers.DataSource = line;
Streamers.Sorted = true;
sr.Close();
Console.ReadLine();
You can use GetFolderPath
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
Also you can check this answer for more information.
Update
Notice that you need Administrator rights to access this folder.
For Access denied error check these two answers:
Number one
The directory %AppData% is a system-protected directory. Windows
will try to block any access to this directory as soon as the access
was not authorized (An access from another user than the
Administrator).
Number two
I would use System.IO.Path.Combine(...) instead of
string.Conact(...) in this situation. Like this...
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"Programım");

I'm unable to reference an uploaded file

Sorry if this is a simple question but I'm still not to competent at coding. Via ASP.net c# I upload a file to Uploads with an UploadHandler.ashx which is working fine. Then I try to reference the file. Before referencing it I check to see if the file exists with
if (File.Exists(filePath))
{
Do stuff;
}
else
{
Do other stuff;
}
When debugging the filePath is showing as "../Uploads/P3301_5_40_4.bin" which is what I am expecting but the if file exists is returning false. Am I entering the file path with an incorrect syntax or is there something else I am messing up? I confirmed the file is there.
File.Exists is probably looking for the physical path to the file on the server. Try using Server.MapPath which maps the virtual path in your website to the physical path on the server.
string physicalPath = Server.MapPath(filePath);
if (System.IO.File.Exists(physicalPath))
{
// do stuff
}
else
{
// handle error
}
You should convert filePath using something like this:
filePath = HttpContext.Current.Server.MapPath(filePath);

Loading files in default Internet browser programmatically

I used this to load a file (html_file.html) from Resources
//string myFile = "C:\\Users\\...\\Resources\\html_file.html"; // this works
var myFile = Path.GetFullPath("html_file.html"); // this doesn't works
//myFile = myFile.ToString();
//myFile = myFile.Replace(#"\", #"\\");
//MessageBox.Show(myFile);
try
{
Process.Start(myFile);
}
catch (Win32Exception noBrowser)
{
if (noBrowser.ErrorCode == -2147467259)
MessageBox.Show(noBrowser.Message);
}
catch (System.Exception other)
{
MessageBox.Show(other.Message);
}
Can someone tell me what's wrong?
EDIT : This works
Build Action = Embedded Resource and Copy to Output Directory = Copy always
string myFile = #".\Resources\html_file.html";
but I still need to have the path Resources with the file. Is there any way to have the 'html_file' inside my .EXE file?
Quite obviously it cannot find the file in the current directory. Make sure the following are correct:
The file is included in your project and its Copy to Output Directory property is set to Copy always or Copy if newer.
Use Application.StartupPath to make sure you are pointing to correct directory, so the first line would become:
Code:
var myFile = Path.Combine(Application.StartupPath, "html_file.html");
In the first method you specify the exact path to your file.
In the second one you ask the framework to create a fullpath.
The framework need to start from somewhere and it choose to start from your current directory but the file is not present there

Deploy an application's xml file with installer or create it on the fly if it does not exist

I am having an xml file like:
<CurrentProject>
// Elements like
// last opened project file to reopen it when app starts
// and more global project independend settings
</CurrentProject>
Now I asked myself wether I should deliver this xml file with above empty elements with the installer for my app or should I create this file on the fly on application start if it does not exist else read the values from it.
Consider also that the user could delete this file and that should my application not prevent from working anymore.
What is better and why?
UPDATE:
What I did felt ok for me so I post my code here :) It just creates the xml + structure on the fly with some security checks...
public ProjectService(IProjectDataProvider provider)
{
_provider = provider;
string applicationPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
_projectPath = Path.Combine(applicationPath,#"TBM\Settings.XML");
if (!File.Exists(_projectPath))
{
string dirPath = Path.Combine(applicationPath, #"TBM");
if (!Directory.Exists(dirPath))
Directory.CreateDirectory(dirPath);
using (var stream = File.Create(_projectPath))
{
XElement projectElement = new XElement("Project");
projectElement.Add(new XElement("DatabasePath"));
projectElement.Save(stream, SaveOptions.DisableFormatting);
}
}
}
In a similar scenario, I recently went for creating the initial file on the fly. The main reason I chose this was the fact that I wasn't depending on this file being there and being valid. As this was a file that's often read from/written to, there's a chance that it could get corrupted (e.g. if the power is lost while the file is being written).
In my code I attempted to open this file for reading and then read the data. If anywhere during these steps I encountered an error, I simply recreated the file with default values and displayed a corresponding message to the user.

Categories