I found I could get a file by:
var files = System.IO.Directory.GetFiles("Some Directory");
The file is one contained within this collection;
However is there a method to get a single file by passing the file path tothis method?
There are alot of ways to directly access a file by path. Here are a few:
string path = // path string here
File.ReadAllText(path);
File.OpenRead(path);
File.OpenWrite(path);
Essentially everything the 'File' class does is related to a single file. Its a static class in the System.IO namespace.
http://msdn.microsoft.com/en-us/library/system.io.file.aspx
http://msdn.microsoft.com/en-us/library/b9skfh7s.aspx
System.IO.File.Open
Related
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>)
I am trying to get the full path a file by its name only.
I have tried to use :
string fullPath = Path.GetFullPath("excelTest");
but it returns me an incorrect path (something with my project path).
I have read somewhere here a comment which says to do the following:
var dir = Environment.SpecialFolder.ProgramFilesX86;
var path = Path.Combine(dir.ToString(), "excelTest.csv");
but I do not know where the file is saved , therefore I do not know its environment.
can someone help me how to get the full path of a file only by its name?
The first snippet (with Path.GetFullPath) does exactly what you want. It returns something with your project path because the program EXE file is located in the project\Bin\Debug path, which is therefore the "current directory".
If you want to search for a file on a drive, you can use Directory.GetFiles, which will recursively search for a file in a directory given a name pattern.
This returns all xml-files recursively :
var allFiles = Directory.GetFiles(path, "*.xml", SearchOption.AllDirectories);
http://msdn.microsoft.com/en-us/library/ms143316%28v=vs.100%29.aspx
http://msdn.microsoft.com/en-us/library/ms143448.aspx#Y252
https://stackoverflow.com/a/9830162/2196124
I guess you're trying to find file (like in windows search), right ?
I'd look into this question - you will find all files that has that string in their filename, and from there you can return full filepath.
var fileList = new DirectoryInfo(#"c:\").GetFiles("*excelTest*", SearchOption.AllDirectories);
And then just use foreach to do you manipulations, e.g.
foreach(string file in fileList)
{
// MessageBox.Show(file);
}
What you're looking for is Directory.GetFiles(), you can read up on it here. The gist of it is, you'll pass in the file path and the file name, and you'll get a string array back. In this instance, you can assume top level with C:\. It should be noted, that if nothing is found, the string array will be empty.
You have passed a relative file name to Path.GetFullPath. Microsoft documentation states:
If path is a relative path, GetFullPath returns a fully qualified path that can be based on the current drive and current directory. The current drive and current directory can change at any time as an application executes. As a result, the path returned by this overload cannot be determined in advance.
You cannot get the same full path name from a relative path unless your current directory is the same each time you invoke the function.
I have an XmlTextReader to read series of XML files to load some information in to my program.
However, in some XML files I have the file name of an image and I want to load that image.
But the problem is the XML file does not have the full path of the image.
<Image id="ImageId" File="Image.bmp" />
<!-- full path is not available. Image is behind XML-->
This means the Image exist where the xml file exists.
for some reason, the only way to get the path of the XML file is to get the path of the XmlTextReader reading the current XML file.
I did some research and I found out you can retrieve the XML path from the XmlTextReader as below:
string path = reader.BaseURI; // this will get the path of reading XML
// reader is XmlTextReader
How can I combine path with the image's path?
I have tried the following way:
string FullImagePath = Path.Combine(reader.BaseURI, imagePath);
These are the values of the variables:
reader.BaseURI is "file:///D:/.../currentXml.xml"
imagePath is "Image.bmp".
Finally, FullImagePath, after assigning the result of Path.Combine is file:///D:/.../currentXml.xml\\Image.bmp, which is not what I expect.
Expected path of the image is: D:/.../Image.bmp, in the same directory as currentXml.xml.
So how can I get the path of the image file?
You have a two different problems that you need to solve separately.
Depending on the API used to consume the image file, a file:// URI path may or may not be supported. So you'd want to make that a local path as explained in Convert file path to a file URI?:
string xmlPath = "file://C:/Temp/Foo.xml";
var xmlUri = new Uri(xmlPath); // Throws if the path is not in a valid format.
string xmlLocalPath = xmlUri.LocalPath; // C:\Temp\Foo.xml
Then you want to build the path to the image file, which resides in the same directory as the XML file.
One way to do that is to get the directory that file is in, see Getting the folder name from a path:
string xmlDirectory = Path.GetDirectoryName(xmlLocalPath); // C:\Temp
Then you can add your image's filename:
string imagePath = Path.Combine(xmlDirectory, "image.png"); // C:\Temp\image.png
Or, in "one" line:
string imagePath = Path.Combine(Path.GetDirectoryName(new Uri(reader.BaseURI).LocalPath),
ImagePath);
Path.Combine(Path.DirectoryName(reader.BaseUri), imagePath)
As you are dealing with resolving URLs I would suggest to use XmlUrlResolver in System.Xml:
string localPath = new XmlUrlResolver().ResolveUri(new Uri(baseUri), imageName).LocalPath;
I already know how to browse for an image using open file dialog. So let's say we already got the path :
string imagePath = "Desktop/Images/SampleImage.jpg";
I want to copy that file, into my application folder :
string appFolderPath = "SampleApp/Images/";
How to copy the given image to the appFolderPath programmatically?
Thank you.
You could do something like this:
var path = Path.Combine(
System.AppDomain.CurrentDomain.BaseDirectory,
"Images",
fileName);
File.Copy(imagePath, path);
where fileName is the actual name of the file only (including the extension).
UPDATE: the Path.Combine method will cleanly combine strings into a well-formed path. For example, if one of the strings does have a backslash and the other doesn't it won't matter; they are combined appropriately.
The System.AppDomain.CurrentDomain.BaseDirectory, per MSDN, does the following:
Gets the base directory that the assembly resolver uses to probe for assemblies.
That's going to be the executable path you're running in; so the path in the end (and let's assume fileName is test.txt) would be:
{path_to_exe}\Images\test.txt
string path="Source imagepath";
File.Copy(System.AppDomain.CurrentDomain.BaseDirectory+"\\Images", path);
\ System.AppDomain.CurrentDomain.BaseDirectory is to provide path of the application folder
Question Background:
I need to copy and paste (move) a file from one folder location to another.
Issue:
The File.Copy method of System.IO requires the that both parameters are of known file locations. I only know one file path location - in this case localDevPath. localQAPath is the folder path where I want the copied file to be moved too.
string localDevPath = #"C:\Folder1\testFile.cs";
string localQaPath = #"C:\Folder2\";
File.Copy(localDevPath, localQaPath);
Can anyone tell me how to go about carrying out this 'copy and paste' method I'm trying to implement.
string localDevPath = #"C:\Folder1\testFile.cs";
string localQaPath = #"C:\Folder2\";
FileInfo fi = new FileInfo(localDevPath);
fi.MoveTo(Path.Combine(localQaPath, fi.Name));
Assuming that these are user-provided paths and you can't simply include the filename in the second path, then you need to extract the last path element from localDevPath and then add it to localQaPath. You could probably do that with Path.GetFilename.
I'm guessing the issue here is that the filename is variable, in which case, you could do something like this to extract the filename from the full path of localDevPath:
string localDevPath = #"C:\Folder1\testFile.cs";
string localQaPath = #"C:\Folder2\";
string[] tokens = localDevPath.Split(#"\");
localQaPath += tokens[tokens.Length-1];
File.Copy(localDevPath, localQaPath);
Documentation on File.Copy is on MSDN. There is an overload that accepts a boolean, to allow overwriting if there is a naming conflict.
If what you want to do is move the file from one location to another, the method you are looking for is MoveTo. It is a method of the FileInfo class. There is a very complete example in the MSDN Library here: FileInfo.MoveTo Example