c# clickOnce xml file not found - c#

C# deployment clicOnce. Setup run xml file not found?
XDocument x = XDocument.Load(#"veri.xml");
image1:
http://www.kgmmp.org/333.jpg

If it is a file in the project, check whether it is copy local from the file's properties. file must be copy local. then you can try the following.
XDocument x = XDocument.Load(#"veri.xml");
string filePath = Path.Combine(
HostingEnvironment.ApplicationPhysicalPath,
#"App_Data\AppSettings.xml"
);

Related

Hide Json file containing GOOGLE_APPLICATION_CREDENTIALS when building executable file in Visualstudio [SOLVED]

currently I am developing a tool that interacts with a Firebase Firestore database. When I want to make the C# Forms Application an executable file I get the .exe but also the json file which contains the Google App Credentials. However, I want to forward the tool so that you can't see the json file or read the contents of the file, so you only need the .exe file. Is there a way to achieve this? For example, define the app credentials in a C# script so that it compiles to the .exe file? If so how?
My current implementation looks like this:
string path = AppDomain.CurrentDomain.BaseDirectory + #"cloudfire.json";
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", path);
The cloudfire.json file is directly contained in the namespace "LUX".
I also tried making the cloudfire.json file a resource, since i read this post but then the problem is, that i can't set the path of the .json, if i try it like that:
var assembly = Assembly.GetExecutingAssembly();
string resourceName = assembly.GetManifestResourceNames()
.Single(str => str.EndsWith("cloudfire.json"));
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", resourceName);
I get the error: System.InvalidOperationException: "Sequence contains no matching element"
Is there maybe a way to set the "GOOGLE_APPLICATION_CREDENTIALS" to the embedded cloudfire.json ressource file?
EDIT:
I solved the problem by adding the "cloudfire.json" file to Resources.resx and changed the modifier to public. Like mentioned here.
Since you can only set the GOOGLE_APPLICATION_CREDENTIALS by using this code:
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "path to file");
I solved it by creating a temporary file:
byte[] resourceBytes = Properties.Resources.cloudfire;
// Write the resource to a temporary file
string tempPath = Path.GetTempFileName();
File.WriteAllBytes(tempPath, resourceBytes);
// Set the GOOGLE_APPLICATION_CREDENTIALS environment variable
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", tempPath);
Add you file as embedded resource with name. And try to read by following code:
var resources = new ResourceManager("<namespace>", Assembly.GetExecutingAssembly());
var obj = resources.GetObject(<embedded_resource_key>);
or
var str = resources.GetString(<embedded_resource_key>)

How to Get current date and create directory Everyday in C#?

get current date and make directory and second when directory is created, in that directory I have to store excel file and also save file as current date.
String Todaysdate = DateTime.Now.ToString("dd-MM-yyyy");
if (!Directory.Exists("C:\\Users\\Krupal\\Desktop\\" + Todaysdate))
{
Directory.CreateDirectory("C:\\Users\\Krupal\\Desktop\\" + Todaysdate);
}
This code have made directory with current date.
But when I want to store file in that directory, it generates the error:
Could not find a part of the path
'D:\WORK\RNSB\RNSB\bin\Debug\22-01-2020\22-01-2020.XLS
Belove path is store excel file that i have to store.
using (System.IO.StreamWriter file = new System.IO.StreamWriter(Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"))
Actually you are making the directory in a path then you are saving the .xls in another path.
You are making the directory using this path:
"C:\\Users\\Krupal\\Desktop\\" + Todaysdate
Then, here the path where you are trying to save the .xls:
Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"
The error shows the problem clearly, it could not fin this path:
D:\WORK\RNSB\RNSB\bin\Debug\22-01-2020\22-01-2020.XLS
While creating the .xls you are omitting the root path, so the process looks for the path 22-01-2020\22-01-2020.XLS in his working directory D:\WORK\RNSB\RNSB\bin\Debug.
You just need to align those paths: I sugget you to use relative paths, so here how you should fix your code:
String Todaysdate = DateTime.Now.ToString("dd-MM-yyyy");
if (!Directory.Exists(Todaysdate))
{
Directory.CreateDirectory(Todaysdate);
}
//then
using (System.IO.StreamWriter file = new System.IO.StreamWriter(Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"))
I presume you are running your WinForms application in Debug mode. This means that your current path is [your application path]\bin\Debug. If you look in file explorer, you will find that an executable has been created there. When using StreamWriter without an absolute file name, the file it tries to create is relative to the current execution path (in your case 'D:\WORK\RNSB\RNSB\bin\Debug'). StreamWriter will create a new file, if one does not exist, but it will not create a new folder, and you are passing it Todaysdate + "\\" which is effectively a new folder. Hence you are getting the error message.
To fix your problem, you need to provide the absolute path to your newly created directory thus:
using (System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\Users\\Krupal\\Desktop\\" + Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"))
Winforms always expect directories inside Debug Folder, since it's EXE file is inside Debug and try to find it inside Debug folder.
In error it clearly shows that it is looking inside "Debug" folder.
Can you check whether File Exists in the mentioned folder created by you in C Drive.
// To Write File
System.IO.File.WriteAllLines(#"C:\Users\Public\TestFolder\WriteLines.txt", lines);
You can follow this MSDN Post, hope it helps, if Yes, please Upvote it
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-write-to-a-text-file

how to read a file from a different project?

how to read a file from a different project?
I have a solution:
Solution1
-MyProject
-MyProject.Artifacts
----Message.XML
-MyProject.Tests
I am attempting to read the contents of Message.XML from MyProject.Tests.
How do I read the contents of Message.XML from MyProject.Tests?
Unfortunately, right now I'm doing something like this, but it's not very pretty:
var currentDir = Directory.GetCurrentDirectory();
var parentDir = Directory.GetParent(Directory.GetParent(currentDir).FullName).FullName;
var parentParentDir = Directory.GetParent(Directory.GetParent(Directory.GetParent(currentDir).FullName).FullName).FullName;
var parentParentParentDir = Directory.GetParent(Directory.GetParent(Directory.GetParent(Directory.GetParent(currentDir).FullName).FullName).FullName).FullName;
You can store a path to the file in app settings of app.config / web.config using that read the file contents.
That way if you need to deploy your software in a different way you have the flexibility
If your path is fixed, you can write the path like "c:\projects\solution ... Message.xml"
If you want a relative path, the simplest way is this:
var DI = new DirectoryInfo("..\\..\\..\\..\\Your Folder\\Message.XML");
This path is started from CurrentDirectory and goes four folders up and the one folder down and finds the file.

Loading an XML file path in C#

I'm trying to load an XML-file, located in a folder in my project (using Visual Studio 2012).
The structure is this:
solutionRoot\
- service\
-- ServiceClass.cs
-- AppValues.xml <-- this is the file I want to load
In my ServiceClass, I'm trying to read from the XML-file with the following code:
public String GetXmlElement(String elementName)
{
[....]
XDocument document = XDocument.Load(#"\service\AppValues.xml");
[...]
}
Which gives the following error, when I'm trying to test the code:
Test method PandaTests.ServiceTest.ReadXmlCanReadXml threw exception:
System.IO.DirectoryNotFoundException: Could not find a part of the path
'C:\Users\MyName\Documents\GitHub\project\Project22\PandaTests\bin\Debug\service\AppValues.xml'.
It's obviously a problem with my path, but I can't figure out how to get the relative path right. I've looked at other questions here on stack overflow, but many of them seem overly involved. Is there an easy way to load the XML-file without giving an absolute path?
When VS runs your program, your working directory is set to the Debug/Release folder, not to your solution root.
You have a couple options that I know of...
Use an absolute path, but you don't want this
Set your file to copy into your working directory on build. You do this by modifying the properties of the file in the solution explorer. Thanks to T.Roland in the comments below: Set Copy to Output Directory to Copy if Newer and set Build Action to Embedded Resource;
Modify your solution's working directory to be your solution root This thread offers different ways to accomplish that.
I faced the same problem and solved it using "Server.MapPath"
For example,
string path=Server.MapPath("~/service/AppValues.xml");
XDocument document = XDocument.Load(path);
Hope it helps.
Bring up the properties in Visual Studio for AppValues.xml. Change "Copy to Output Directory" to "Copy if Newer", and build the project.
check this
XDocument document = XDocument.Load(#"..\service\AppValues.xml");
Set the build action of the xml file to be "Embedded resource" and then reference using this code
private static UnmanagedMemoryStream GetResourceStream(string resName)
{
var assembly = Assembly.GetExecutingAssembly();
var strResources = assembly.GetName().Name + ".g.resources";
var rStream = assembly.GetManifestResourceStream(strResources);
var resourceReader = new ResourceReader(rStream);
var items = resourceReader.OfType<DictionaryEntry>();
var stream = items.First(x => (x.Key as string) == resName.ToLower()).Value;
return (UnmanagedMemoryStream)stream;
}
var file = GetResourceStream("appValues.xml");
When adding a file to Visual Studio project, by default it is not copied to the generated output. As such, you need to set to either copy the file or do so manually.
To set the file to automatically copy, select it in solution explorer, right click and select properties. Update the value for "Copy to Output Directory" to "Copy Always". This will ensure a copy of the file is available at runtime in a subfolder of the resultant solution.
You can then load the file using something like:
string path = System.Io.Path.Combine(Application.StartupPath, #"\service\AppValues.xml");
XDocument doc = XDocument.Load(path);
I solved it in 2 steps. I'm using MVC and I had to use this in a class file.
1) String path
=HttpContext.Current.Server.MapPath("~/App_Data/yourxmlfilename.xml");
XDocument doc = XDocument.Load(path);
2) Change XML file properties
Build Action: Content
Copy to Output Directory: Copy always

Programmatically Access a File on ASP.NET MVC4

As part of an ASP.NET MVC4 project I need to be able to read from and write to some XML files. I have trouble finding / accessing the files I need.
I've created a demo project to which I've added a folder /Documents containing some XML files.
So in the same project I have a folder /Classes with my class that should read the XML files using XDocument.load().
Here is what I'd like to do (and how I thought it should work):
string path = "/Documents/test.xml"; // Doesn't work
XDocument xml = XDocument.load(path);
However, this doesn't work. Not with "/Documents", "Documents" or "~/Documents".
Supplying the full path works, but not very useful if the website is going to be deployed in other environments.
string path = "D:/Projects/Demo/Demo/Documents/test.xml"; // Works
XDocument xml = XDocument.load(path);
Any suggestions how I can access the files using some kind of relative path?
use Server.MapPath to get the absolute path.
string path = Server.MapPath("/Documents/test.xml");
XDocument xml = XDocument.load(path);
Use HttpContext.Current.Server.MapPath
string path = HttpContext.Current.Server.MapPath("/Documents/test.xml");
Have you tried:
var path = Server.MapPath("/Documents/test.xml");

Categories

Resources