Finding a xml config file - c#

I am trying to check whether an xml config file exists.
The file has the name MyApp.exe.config
I am using
public static bool FileExistsCheck(string filename, string filepath = "")
{
if (filepath.Length == 0)
filepath = Directory.GetCurrentDirectory();
return File.Exists(filepath + "\\" + filename);
}
this returns false despite the file existing
Can anyone advise on the correct way of checking whether or not this file exists?

try
return File.Exists(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)
msdn

at runtime Directory.GetCurrentDirectory() will return debug/release/bin dir path. Does the config XML file reside in those folders?

You can just check for File.Exists(CONFIGFILENAME). Because .net takes the relativ path from the current directory

For first I recommend you to use Path.Combine(path, fileName); to create paths.
For second use Application.StartupPath, not Directory.GetCurrentDirectory.
For third, make sure that your application folder contains MyApp.exe.config.

Please consider this method:
public static bool isFileExist(string filePath)
{
if (File.Exists(filePath))
return true;
else return false;
}
I think the culprit on your method is this:
filepath = Directory.GetCurrentDirectory();

Related

creating a textfile and cannot identify the location the created file goes

What is wrong with this code? The text file is not created in the bin\Debug directory!
string path = Environment.CurrentDirectory + "/" + "Contacts.txt";
if (!File.Exists(path))
{
File.CreateText(path);
MessageBox.Show("file created successfully");
}
using (StreamWriter sw = new StreamWriter("path", true))
{
sw.WriteLine(txtCntname1.Text + "," + txtCntnum1.Text + "," + txtCntnum2.Text + "," + txtCntnum3.Text + ",");
sw.Close();
}
You have two ways of calculating EXE's directory:
1) Implicit
You can use only the file name. In this case, the file will be created in the same folder with EXE file:
File.CreateText("Contacts.txt")
2) Explicit
If you need reliable way to get the EXE's directory, then you need to use AppDomain:
string exe_dir = AppDomain.CurrentDomain.BaseDirectory;
Then, instead of manually concatenating strings to form a path, use Path.Combine method:
string file_path = Path.Combine(exe_dir, "Contact.txt");
The code (Assembly.GetExecutingAssembly().Location), offered by #TobiasTengler, won't work, for instance, for Excel/Word add-in.
Aside from that path should probably not be in quotes here:
using (StreamWriter sw = new StreamWriter("path", true))
Do not use Environment.CurrentDirectory! It does not always represent the directory you started your executable from, since it only represents your working directory.
Please use Assembly.GetExecutingAssembly().Location to get the full path of the executing assembly and then extract only the directory from it, using:
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
Alternatively you could also use AppDomain.CurrentDomain.BaseDirectory for identifying the directory your application is residing in.
Of course not using an absolute path is a possibility as well, you can create your file using a relative path, by not specifying any directory:
File.CreateText("Contacts.txt")
EDIT:
Seeing how you formed your path, please also use Path.Combine to build your paths:
var appBaseDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var contactsFilePath = Path.Combine(appBaseDir, "Contacts.txt");

Copying a file from one location into a folder in Solutions Explorer using asp.net

I am working on an asp.net project using c# and I need to copy a file from an arbitrary location which is determined by the file upload dialog box.
I need to make an exact copy of the file in a folder that is located in the Solutions Explorer. Below is the code I am using.
string filename = txt_lesson_title.text;
string sourcepath = _Uploadedfile.PostedFile.FileName.ToString();
string targetPath = HttpContext.Current.Server.MapPath("/destFolder/");
File.Copy(sourcePath, targetPath + fileName);
The above code runs without reporting any errors but I cannot see the copied files in the destination folder. Any help will be deeply appreciated.
Thanks
You don't need to copy the file, you need to save a copy of it.
You can do this
if the file is coming to your controller, you controller should have arguments like HttpPostedFileBase or HttpPostedFileBase[] depending on if you are saving one or more
if you are saving one,
public ActionResult Step(FormCollection collection, HttpPostedFileBase file) {
//HttpPostedFileBase file; //this comes from you controller argument
var directory = "~/Uploads/";
//this if statement can be optional
if(!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(directory)))
{
Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(directory));
var virtualPath = directory + "/" + <your file name here>;
var filePath = System.Web.HttpContext.Current.Server.MapPath(virtualPath);
//if the file exists already, delete and replace it with the new one
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
file.SaveAs(filePath);
}
else {
//do as above without the create directory
}
}

C# absolute path with streamReader

I have an issue with the reading a file in C#
I have two different locations for .exe (both different) and reading the same .xml file. So when I give the path like this:
TextReader textReader = new StreamReader(#"../../../TrajectoryGen/obstacleList.xml");
it is able to read from one location ( which is 3 folders behind as used in the path) but not from another location (which is only 2 folders behind)
How do I fix this problem so that it works from both folders?
First way, this relies on you knowing one of the parent folder's names.
const string FILENAME = "obstacleList.xml";
const string FOLDER = "TrajectoryGen";
string path = Path.GetFullPath(System.Reflection.Assembly.GetExecutingAssembly().Location);
do
{
path = Path.GetDirectoryName(path);
} while (!Path.GetFileName(path).Equals(FOLDER, StringComparison.OrdinalIgnoreCase));
string filepath = String.Format("{0}{1}{2}", path, Path.DirectorySeparatorChar, FILENAME);
^^ You can also use a partial path in the FILENAME like the example below incase you need to into directories once you are at your "base" folder that you know the name of.
Second way blindly continues up directories
const string FILENAME = #"TrajectoryGen\obstacleList.xml";
string path = Path.GetFullPath(System.Reflection.Assembly.GetExecutingAssembly().Location);
string filepath;
do
{
path = Path.GetDirectoryName(path);
//pump
filepath = String.Format("{0}{1}{2}", path, Path.DirectorySeparatorChar, FILENAME);
} while (!File.Exists(filepath));
Both require "using System.IO;" and both have no error handling implemented and will throw NullReferenceException if the file/folder is not found.
I purposely used the do-while loop because the definition of path will included the executable name.

How to combine two path

I have the code below and I get the result like this
C:\\Users\\Administrator\\Projects\\CA\\Libraries\\ConvertApi-DotNet\\Example\\word2pdf-console\\bin\\Release\\\\..\\..\\..\\..\\test-files\\test.docx
The file is found but I would like to show user this path and the formating is not user friendly. I would like to get
C:\\Users\\Administrator\\Projects\\CA\\Libraries\\test-files\\test.docx
I have tried to use Path.Combine but it do not work.
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
string inFile = baseDirectory + #"\..\..\..\..\test-files\test.docx";
You could use a combination of Path.Combine and Path.GetFullPath:
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
var file = #"..\..\..\..\test-files\test.docx";
string inFile = Path.GetFullPath(Path.Combine(baseDirectory, file));
Description
You say that the file is found.
Then you can use FileInfo (namespace System.IO) for that.
Sample
FileInfo f = new FileInfo(fileName);
f.Exists // Gets a value indicating whether a file exists.
f.DirectoryName // Gets a string representing the directory's full path.
f.FullName // Gets the full path of the directory or file.
More Information
MSDN - FileInfo Class

Copy file to a different directory

I am working on a project where I want to copy some files in one directory to a second already existing directory.
I can't find a way to simply copy from one folder to another. I can find copy file to a new file, or directory to a new directory.
The way I have my program set up right now is I copy the file and leave it in same directory, then move that copy to the directory that I want.
Edit:
Thanks everyone. All of your answers worked. I realized what I did wrong, when i set the destination path I didn't add a filename. Everything works now, Thanks for the super speedy responses.
string fileToCopy = "c:\\myFolder\\myFile.txt";
string destinationDirectory = "c:\\myDestinationFolder\\";
File.Copy(fileToCopy, destinationDirectory + Path.GetFileName(fileToCopy));
File.Copy(#"someDirectory\someFile.txt", #"otherDirectory\someFile.txt");
works fine.
MSDN File.Copy
var fileName = "sourceFile.txt";
var source = Path.Combine(Environment.CurrentDirectory, fileName);
var destination = Path.Combine(destinationFolder, fileName);
File.Copy(source, destination);
Maybe
File.Copy("c:\\myFolder\\myFile.txt", "c:\\NewFolder\\myFile.txt");
?
This worked for me:
string picturesFile = #"D:\pictures";
string destFile = #"C:\Temp\tempFolder\";
string[] files = Directory.GetFiles(picturesFile);
foreach (var item in files)
{
File.Copy(item, destFile + Path.GetFileName(item));
}
I used this code and it work for me
//I declare first my variables
string sourcePath = #"Z:\SourceLocation";
string targetPath = #"Z:\TargetLocation";
string destFile = Path.Combine(targetPath, fileName);
string sourceFile = Path.Combine(sourcePath, fileName);
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!Directory.Exists(targetPath))
{
Directory.CreateDirectory(targetPath);
}
// To copy a file to another location and
// overwrite the destination file if it already exists.
File.Copy(sourceFile, destFile, true);
If the destination directory doesn't exist, File.Copy will throw. This version solves that
public void Copy(
string sourceFilePath,
string destinationFilePath,
string destinationFileName = null)
{
if (string.IsNullOrWhiteSpace(sourceFilePath))
throw new ArgumentException("sourceFilePath cannot be null or whitespace.", nameof(sourceFilePath));
if (string.IsNullOrWhiteSpace(destinationFilePath))
throw new ArgumentException("destinationFilePath cannot be null or whitespace.", nameof(destinationFilePath));
var targetDirectoryInfo = new DirectoryInfo(destinationFilePath);
//this creates all the sub directories too
if (!targetDirectoryInfo.Exists)
targetDirectoryInfo.Create();
var fileName = string.IsNullOrWhiteSpace(destinationFileName)
? Path.GetFileName(sourceFilePath)
: destinationFileName;
File.Copy(sourceFilePath, Path.Combine(destinationFilePath, fileName));
}
Tested on .NET Core 2.1
NET6 - Extension method
[DebuggerStepThrough]
public static FileInfo CopyToDir(this FileInfo srcFile, string destDir) =>
(srcFile == null || !srcFile.Exists) ? throw new ArgumentException($"The specified source file [{srcFile.FullName}] does not exist", nameof(srcFile)) :
(destDir == null || !Directory.Exists(destDir)) ? throw new ArgumentException($"The specified destination directory [{destDir}] does not exist", nameof(destDir)) :
srcFile.CopyTo(Path.Combine(destDir, srcFile.Name), true);

Categories