views:

859

answers:

3

While implementing XML file reading/writing in my application I saw that when I call XElement.Save("myfile.xml") it will overwrite an existing file.

Is this behavior default for all methods that Save files in C#/ASP.NET or does it depend on the permissions given to ASP.NET?

If my app will be deployed by different people on different hosting setups, what factors should I take into consideration for the possible limitations (if any) that can be placed on my app when reading/writing files?

Will a certain server setup only allow me to overwrite existing files when I delete the old one?

When saving files that will be used later by my application, is App_Data the safest folder to save them in?

A: 

you can have a work around to test if the file exist or not.

Henry Gao
Would I need to do that anytime I overwrite a file, or is it default that overwriting occurs?
Baddie
+1  A: 

The default behaviour issue is really a separate beastie from the permissions issue...

There is no single guiding principle for the default behaviour wrt overwriting in .NET Framework methods that save data to files. For any given method that you invoke, you should investigate the default behaviour. If you don't like it, you can look for a workaround. For example, the XmlDocument.Save method has an overload that accepts a stream instead of a file path. You can use this by providing a FileStream opened using a FileMode other than Create (which is what is used by the XmlDocument.Save(string) overload).

Regardless of the file creation and/or modification approach that a method attempts to use, the file modification attempt will fail (with an exception raised) unless both of the following conditions are met:

  1. The user account under which the code is running must have permissions to create/delete/modify (as attempted by the code) the file.
  2. The code itself must have adequate Code Access Security permissions for the file modification operation.
Nicole Calinoiu
A: 

Is this behavior default for all methods that Save files in C#/ASP.NET: Usually, it should be documented in the MSDN entry of the method. For example, the documentation of the StreamWriter constructor explicitly mentions that files are overwritten. Unfortunately, XElement.Save lacks such a specification, so strictly speaking, you probably shouldn't rely on this behavior and use, for example, the workaround described by Nicole.

Personally, I do not believe that this depends on the server and that XElement.Save will always overwrite the file, but to make sure, you'd have to examine the source code of XElement.Save (using a disassembler, a decompiler or the .NET reference source). However, even then, relying on this behavior would be bad practice since it is undocumented and might change in future releases of the Framework.

About the directory: Yes, App_Data is where files created by your application should go.

Heinzi