i'm trying to include in my setup (pubish) an excel file, that is on my bin/debug folder.
When I click on properties, I have them as Build Action: Content and Copy to output directory: Copy always.
On my Application files I have:
my code looks like this:
string UDOFileName = System.AppDomain.CurrentDomain.BaseDirectory + "UDOs.xlsx";
if (System.IO.File.Exists(UDOFileName))
{
// Do some Work
}
else
{
MessageBox.Show("File not found");
}
When I run my program it works, but when I create the setup and run my application I get the "File not found" message.
What am I doing wrong?
St. Pat gave me the idea to switch to release mode and I changed the code to
string UDOFileName = System.AppDomain.CurrentDomain.BaseDirectory +
#"bin\Debug\UDOs.xlsx";
Now everything is working
Related
firstly apology if this has already been answered and I am duplicating the question. I have tried to find the answer to my issue but have failed and none of the auto-suggestions answers my problem.
I have my main project (XAML) and also a class library project called FileStore for files. The class library project is referenced into the main project and I have images and icon file in the class library project that I can access with no issues in my main project, however, I struggle to get the content of a txt file from the CL project to display in a label on the main project. I get the error: the system could not find the file and from the error, I can see that it is trying to look for a file in the main project bin\debug folder
I tried to follow this previous post which seemed to partly answer my issue but to no avail sadly.
Get relative file path in a class library project that is being referenced by a web project
The txt file Build action is set to: Resource and Copy to Output Directory set to: Copy Always.
As I mentioned I have the FileStore project referenced in my main project and the images work fine.
Below is the code I am using, I have tried different variations such as:
\Resources\textFile.txt and \textFile.txt, still no luck.
'''
public static string ReadFileinClLibr()
{
var buildDir =
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var filePath = buildDir + #"\textFile.txt";
return File.ReadAllText(filePath);
}
'''
For comparition here is the path for the image files that works, but I cannot get it to work with the txt file, as the error reads: the given paths format is not supported..
'''
#"pack://application:,,,/FileStore;component/Resources\textFile.txt"
'''
I want to be able to input the content of the text file from the class library project to the label in the main xaml project.
At the moment compiler keeps looking for this file in a debug folder of the main project, what I want is, for the compiler to look for the txt file in a CL FileStore project
In order to access the file all the time, we have to have the file copied to the debug folder. Right click the file from solution explorer change the properties then try to access the file from the executing assembly location.
StringBuilder bodyContent = new StringBuilder();
string fileName = "myfile.txt";
try
{
string filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), fileName);
using (StreamReader sr = new StreamReader(filePath))
{
// Read the stream.
bodyContent.Append(sr.ReadToEnd());
}
}
catch(Exception ex)
{
Console.WriteLine(String.Format("{0} # {1}", "Exception while reading the file: " + ex.InnerException.Message, DateTime.Now));
throw ex;
}
Thanks to the post from #Sreekanth Gundlapally I have managed to fix my issues. I have mostly drawn on from the answer provided by #Sreekanth Gundlapally but there is one important bit missing. The string fileName should include any subfolders that the resource file is within in the Class Library Project, for example in my case the folder was named 'Resources' so the code should look like this:
string fileName = #"Resources/myfile.txt";
try
{
string filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), fileName);
using (StreamReader sr = new StreamReader(filePath))
{
// Read the stream.
bodyContent.Append(sr.ReadToEnd());
}
I have also cleaned and rebuilt solution after which it all worked a charm.
Also a side note, anyone trying this and getting funny characters make sure your file's encoding is set to UTF-8 as this is the default encoding used by StreamReader, otherwise your file content may not be read correctly if it contains signs such as apostrophe.
I'm trying to create a file folder through the program to hold pdfs that I will later generate. I am doing so in my local and internal server, using the same code to do so:
if (!Directory.Exists(pathName))
Directory.CreateDirectory(pathName);
It works fine if it goes to local, but when I send it to the internal path the
Directory.CreateDirectory(pathNameInternal);
creates a file, not an actual file folder which is causing errors later in the code when it tries to access that named folder.
I have no idea why it is creating a file, anyone have any ideas?
Code from comment:
theOut = #"C:\inetpub\wwwroot\UserDownloads";
Directory.CreateDirectory(theOut + "\\" + DBName);
if (copyInternal == true)
{
theOutInternal = #"\\192.168.2.40\c$\inetpub\wwwroot\UserDownloads";
Directory.CreateDirectory(theOutInternal);
Directory.CreateDirectory(theOutInternal + "\\" + DBName);
}
I'm attempting to do two things. I want to embed a text file into my project so that I can utilise it and modify it, but at the same time I don't want to have to package it when I send the project out to users (I.E included in the exe file).
I've had a look around and there's been multiple questions already but I just cant seem to get any to work. Here's the steps I've taken so far;
Added the text file to my "Resources Folder"
Build action to "Content" and output directory to "Do not copy"
I then try to access the file in my code;
if (File.Exists(Properties.Resources.company_map_template))
{
MessageBox.Show("Test");
var objReader = new StreamReader(Properties.Resources.company_map_template);
string line = "";
line = objReader.ReadToEnd();
objReader.Close();
line = line.Replace("[latlong]", latitude + ", " + longitude);
mapWebBrowser.NavigateToString(line);
}
The MessageBox never appears which to me means that it cannot find the file and somewhere somehow I've done something wrong. How can I add the file into my project so I don't need to distribute with an exe whilst being able to access it in code?
I would use the following:
BuildAction to None (not needed)
and add your file to Resources.resx under files (using DragAndDrop from SolutionExplorer to opened Resources.resx)
Access to your Text:
using YOURNAMESPACE.Configuration.Properties;
string fileContent = Resources.company_map_template;
Then you're done. You don't need to access through StreamReader
I'm trying to write a small console app tool that unzips an archive containing multiple files/folders/other archives and arrange it's contents in another way.
I unzip the root file with ZipFile.ExtractToDirectory method from System.IO.Compression.FileSystem library:
public static void UnzipPackage(string packagePath, string targetPath)
{
try
{
ZipFile.ExtractToDirectory(packagePath, targetLocation);
Console.WriteLine("Unzipping file {0} complete.", packagePath);
}
catch (DirectoryNotFoundException)
{
Console.WriteLine("Directory was not found.");
}
catch (FileNotFoundException)
{
Console.WriteLine("File was not found.");
}
}
After running this method on my package, I want to copy a file which was in this package in a subfolder.
According to MSDN I do this:
if (!Directory.Exists(targetLocation + #"READY\PHOTO"))
{
Directory.CreateDirectory(targetLocation + #"\READY\PHOTO");
}
if (Directory.Exists(targetLocation + #"\MAIN\PHOTO"))
{
string[] files = Directory.GetFiles(targetLocation + #"\MAIN\PHOTO");
foreach (var file in files)
{
string fileName = Path.GetFileName(file);
string destFile = Path.Combine(targetLocation + #"\MAIN\PHOTO", fileName);
File.Copy(file, destFile, true);
}
}
Both MAIN and READY are my subdirectories where whole package goes ("main") and sorted files go ("ready").
However, when running this, the zip file is not yet unzipped - an exception occurs showing it can't access the file specified even though it grabbed it's name from Directory.GetFiles(). The folder created when unzipping the zip file shows only after I terminate my console app (no wonder it can't access it).
So the big question is - how can I wait for the unzipped folder to show up? I tried using Thread.Sleep(), but it doesn't affect the flow anyhow - an exception still occurs, and the folder shows only after I terminate the app.
Your error is here:
string destFile = Path.Combine(targetLocation + #"\MAIN\PHOTO", fileName);
Should be:
string destFile = Path.Combine(targetLocation + #"\READY\PHOTO", fileName);
You're attempting to copy the file to the same location.
I'm assuming your getting an IOException something like "The process cannot access the file...because it is being used by another process."
It looks to me that there is a problem in your copy method. It looks like your from and to paths are essentially the same. So the system cannot overwrite the file, because you currently have it open for reading.
Just to be clear - the issue is not related to unzipping! In the example you have written the variable file and destFile are going to be the same - and they need to be different.
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