Could not find xml file - c#

I'm studing wcf. In my test project Service read data from xml file and then send it to client. Data is array of type "myClass".
Service class has a function
Collapse | Copy Code
private XDocument GetDB()
{
string filePath = "SampleDB.xml"
return XDocument.Load(filePath);
}
This function works when I run the service application. But when I call service from client it doesn't work.
The copy of xml file located in bin->debug folder. but when i run programm, I see exception like this
Could not find file 'C:\Program Files (x86)\Microsoft Visual Studio
10.0\Common7\IDE\SampleDB.xml'.
How can I solve this?

Obviously, give the full path to your file, should end with bin\debug\SampleDB.xml

You have to specify the xml file using Server.MapPath.
string filePath = Server.MapPath("SampleDB.xml");
That's the solution of "Could not find file 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\SampleDB.xml'.

Related

Excel files are not being read when executing Selenium C# Scripts on Azure Releases

I have some Selenium C# tests hosted on Azure which they need to look for the pre-built excel file in project tree, stored inside bin folder, to execute some file upload validation scenarios.
When they are executed locally these scenarios pass without any problem, but when it comes to be executed on the Azure they receive the following error.
invalid argument: File not found : D:\a\r1\a_Selenium_Tests\TestApplication\bin\Debug\netcoreapp3.1\Files\SC003_CT014_ActiveEmployees.xlsx
The files do exists in the following path: ...\bin\Debug\netcoreapp3.1\Files...
And the code I use to them is:
string root = Directory.GetCurrentDirectory() + "\\Files\\" + file;
Do you know if there's a missing file configuration or building the filePath in another way?
Thanks for your help :D
Directory.GetCurrentDirection() returns the current working directory, not the folder in which the DLL file resides. The current working directory is a different thing. In your case, the current working directory is probably something like D:\a\r1\. Instead, you need to get the folder in which the test assembly resides:
var binDirectory = Path.GetDirectoryName(GetType().Assembly.Location);
// ^^^^^^^^^
var excelFilePath = Path.Combine(binDirectory, "Files", "SC003_CT014_ActiveEmployees.xlsx");
Note: Replace GetType() with typeof(ClassName) if you are executing your code from a static method, or you would like to specify a path to a different assembly than the one that is currently executing.

how to reference file by path in published c# visual studio build

I have a file path which I access like this
string[] pathDirs = { Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..\\")),
"config", "file.txt" };
string pathToFile = Path.Combine(pathDirs);
When I run the build from within visual studio it gets the config directory from the root directory of the project but when I publish the build and run the program from the published build I get the error
System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Users\<user>\AppData\Local\Apps\2.0\GA3VWRPE.G83\KDK3Q6QC.VP1\sv20..tion_333839f4362dc717_0001.0000_958d209d94853f42\config\file.txt'.
I'm unsure how to access this directory and file in the published build. How would I do this?
To get the path to the executable, you can use Assembly.GetExecutingAssembly().Location, which could be incorporated into your code like:
string filePath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(
Assembly.GetExecutingAssembly().Location), "..", "..", "config", "file.txt"));
Thanks to #ManiVI for that comment.
Go to Solution Explorer and click Show All Files
Go to file.txt, right-click and select Include In Project
in Properties
Build Action: Content,
Copy To Output Directory: Copy always
Once I followed these steps the published program managed to find file.txt.

File ReadAllText is getting a wrong path (C#)

I have a local project that in the future will be in a pipeline.
Because of this, I need to use a relative path to get and read a json file.
But using the File.ReadAllText I'm obtaining the following answer:
> File.ReadAllText("MyJsonFiletoRead.json", Encoding.Default)
System.IO.FileNotFoundException: Could not find file 'C:\Users\15071\MyJsonFiletoRead.json'
Note that 'C:\Users\15071' is not the project folder, this is my windows user folder.
My struct is here:
C:\Projetcs\MyProjectTest -->> Project folder
C:\Projetcs\MyProjectTest\MyClass.cs -->> The class where I'm calling the ReadAllText
C:\Projetcs\MyProjectTest\MyJsonFiletoRead.json -->> My json file that I'm trying to find
I have tried the following commands to check my PATH, but all answer is wrong:
> Environment.CurrentDirectory
"C:\\Users\\15071"
> Directory.GetCurrentDirectory()
"C:\\Users\\15071"
AppDomain.CurrentDomain.BaseDirectory
"c:\\program files (x86)\\microsoft visual studio\\2019\\community\\common7\\ide\\commonextensions\\microsoft\\managedlanguages\\vbcsharp\\languageservices\\DesktopHost\\"
Has somebody a solution to fix this?
Note: If I use the full path, it works:
File.ReadAllText("C:/Projetcs/MyProjectTest/MyJsonFiletoRead.json", Encoding.Default)
If the file is located at the same folder of your executable file, you just need to pass the file name:
File.ReadAllText("MyJsonFiletoRead.json", Encoding.Default);
If the file is located at a relative path from the folder where your executable file is located, you can get the Assembly Location and combine it with a relative path:
var path = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "..\\..\\MyJsonFiletoRead.json");
File.ReadAllText(path, Encoding.Default);
You need to find the current folder and then read the file
var currentFolder = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)
File.ReadAllText(currentFolder + "/MyJsonFiletoRead.json")

a file cannot be deleted and copy and move do not work in C# VS2013

I am trying to copy a file in same folder from C# VS2013 on win7.
string myFile = #"C:\Temp\MyFile.txt"
if (File.Exists(myFile))
{
File.Delete(myFile);
}
File.Move(myFileSource, myFile);
I got error:
Additional information: Cannot create a file when that file already exists.
I checked the folder and found that the file "myFile.txt" is still there after deleting.
If i used:
File.Copy(myFileSource, myFile, true);
Error:
Additional information: Access to the path 'C:\Temp\myFile.txt' is denied.
Why ? thanks
Run visual studio as administrator. It's likely a security issue related to UAC.
You may also want to consider writing the file to somewhere where is will work for all such as:
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

Windows service accessing invalid directory with StreamReader

I am reading a file that is located in the same directory as my executable using a StreamReader with the following method:
StreamReader reader=new StreamReader(".\\file.txt"); //NOTE: 2nd backslash is escape character in C#
When I do this in the debug environment, it reads the file fine, but when I install the service it tries to read the file in C:\Windows\System32\ as if the working directory is set to that path, but in the services properties there is no working directory option. I'm guessing it's using the working dir of sc.exe.
Is there a way I can get it to resolve to the location of the current executable using relative file paths? Because the service might be placed in different locations based on deployments.
Yes, working directory of a service is %WinDir%\System32.Also GetModuleFileName() will return incorrect result because your service is hosted by another executable (by chance placed in that directory too).
You have to find executing assembly and its location, longer to describe than to do:
string assemblyPath = Assembly.GetExecutingAssembly().Location;
Now just extract directory name and combine with file you want:
string path = Path.Combine(Path.GetDirectoryName(assemblyPath), "file.txt");

Categories