c# : find file with variable part in its name - c#

I have a folder location corresponding to the variable "path".
In this folder, I have a lot of files, but only one called "common.build.9897ytyt4541". What I want to do is to read the content of this file, so with the following, it's working :
string text = File.ReadAllText(Path.Combine(path, "common.build.9897ytyt4541.js"));
The problem is, that the part between "build" and "js", change at each source code compilation, and I am getting a new hash, so I would like to replace the previous code, to have something working at each build, whatever the hash is, I thought to regex but this is not working :
string text = File.ReadAllText(Path.Combine(path, #"common.build.*.js"));
Thanks in advance for your help

If you know you'll only find one file you can write something like this (plus error handling):
using System.Linq;
...
var filePath = Directory.GetFiles(path, "common.build.*.js").FirstOrDefault();
string text = File.ReadAllText(filePath);

No, you need to use the exact filename with using File.ReadAllText. Instead, you need to search for the file, for this you can use Directory.GetFiles, for example:
var matches = Directory.GetFiles(path, "common.build.*.js");
if(matches.Count() == 0)
{
//File not found
}
else if(matches.Count() > 1)
{
//Multiple matches found
}
else
{
string text = File.ReadAllText(matches[0]);
}

Related

Trying to search for specific value within text file

I'm trying to search for a specific value within an array of files. I'm not sure what I'm missing here, but some insight would be great.
I've tried containing all lines from each file into an array that can be read from within an if statement.
void getAssetTag()
{
string path = #"\\SERVER\SHARE\FOLDER";
DirectoryInfo d = new DirectoryInfo(path);//Grabbing Directory
FileInfo[] Files = d.GetFiles("*.txt"); //Getting Text files
foreach (FileInfo file in Files)
{
string[] asset = File.ReadAllLines(file.FullName);
if (asset.Contains(AssetT.Text) == true) {
string allinfo = File.ReadAllText(file.FullName);
Results.Text = allinfo;
}
}
}
The results should output the entire data from the text file contained within AssetT.Textinto Results.Text.
asset is a string[], where each string is a line of text. When you do if (asset.Contains(AssetT.Text)), you're comparing an entire line to AssetT.Text.
If you want to find out if any single line contains AssetT.Text, then we need to call Contains on the line, not the array:
if (asset.Any(line => line.Contains(AssetT.Text))
Also, you're ending up reading the file twice here, once when you do ReadAllLines, and again when you do ReadAllText. Since it seems you will always read the whole file (either to determine that the file doesn't contain the text, or to get all the contents because it does contain the text), you should just do it once.
If you use File.ReadAllText in the beginning, now we have a string representation of the entire file which we can call .Contains on:
foreach (FileInfo file in new DirectoryInfo(path).GetFiles("*.txt"))
{
string asset = File.ReadAllText(file.FullName);
if (asset.Contains(AssetT.Text))
{
Results.Text = asset;
// No use reading more files unless we're going
// to save the contents to another variable
break;
}
}
Note that we break out of the loop since it appears you're setting the contents of the file to a single field of some class, so searching for more files will just overwrite any previous results found.
This can be simplified further using System.Linq extension methods and method chaining. We can also use Directory.GetFiles (which returns a list of file paths) instead, since we don't need a full-blown FileInfo object:
Results.Text = Directory
.GetFiles(path, "*.txt")
.Select(File.ReadAllText)
.FirstOrDefault(fileText => fileText.Contains(AssetT.Text)) ?? Results.Text;

to get the file names in a directory (without getting path) in c#

i want to store the name of all file present in c:\test\ in a string array s[]
let there are files name a1.txt , a2.txt , a3.txt ... in c:\test
i want to store in s[0]= a1.txt s[1]= a2.txt and like that
i have used the code
s = Directory.GetFiles(#"c:\\test");
but it makes s[0]= c:\test\a1.txt
i dont want c:\test , i only want a1.txt
so is there any method to store only the file name but not the path of the file
i would also like to know if there is any method to remove some characters from each string of a string array
like cutting 5 characters from the beginning of each string of a string array this may also solve my problem.
Use GetFileName to extract file name from path. Like below
string[] s = Directory.GetFiles(#"c:\\test");
foreach (string filename in s)
{
string fname = Path.GetFileName(filename);
}
maybee duplicate from hare..
any way #Vasea gives us :
Directory.GetFiles(#"c:\test", "*", SearchOption.TopDirectoryOnly).Select(f => Path.GetFileName(f));

C# get a textfile from EACH folder,

I have a folder structure similar to this:
HostnameA->DateTimeA->hashdumpDateTimeA.txt
HostnameA->DateTimeB->hashdumpDateTimeB.txt
HostnameA->DateTimeC->hashdumpDateTimeC.txt
HostnameA->DateTimeD->hashdumpDateTimeD.txt
My Goal:
Given a folder(in this case HostnameA) i need to:
1) Get each hashdumpDateTime.txt filename and place it in a String array -Assumed the file always exist in all folder-
2) Generate DropDownBox using the array (I can figure this out)
3) When user selects a filename via dropdownbox, it will fill my datagridview with the
contents (I can figure this out)
So my problem really is the #1 since i don't know how to make a loop to check the filename coming from a HostnameA folder, I need to know this since the DateTime of these filenames changes
I really appreciate the future help, thanks and cheers =)
You can use Directory.GetFiles method
var files = Directory.GetFiles("directoryPath","*.txt",SearchOption.AllDirectories)
That will give you all file names.If you don't want just names for example if you want file's full path, and some other attributes (like CreationTime, LastAccessTime) use DirectoryInfo class
DirectoryInfo di = new DirectoryInfo("path");
var files = di.GetFiles("*.txt",SearchOption.AllDirectories)
That will return an array of FileInfo instances.Then use a loop and do what you want with the files.
You doesn't need to know the exact name of DirectoryName or FileName, using a for loop and a searchPattern instead.
private string[] GetFileNames(string folder)
{
var files = new List<string>();
foreach (var dateTimeFolder in Directory.GetDirectories(folder))
{
files.AddRange(Directory.GetFiles(dateTimeFolder, "hashdump*.txt"));
}
return files.ToArray();
}

Only include later subdirectories in file string C#

I'm trying to write a nifty content loader in XNA to avoid having to individually load each asset. However, I'm having trouble describing directory locations because the default directory for File operations is the location of the exe, but XNA's Content.Load uses a default directory of the Content folder.
foreach (string subD in Directory.GetDirectories("..\\..\\..\\..\\Happy WorkerContent\\gfx\\", "*.*", SearchOption.AllDirectories))
{
foreach (string s in Directory.GetFiles(subD))
{
string file = Path.GetFileNameWithoutExtension(s);
if (Enum.IsDefined(typeof(Tex), file))
{
Console.WriteLine(subD);
Console.WriteLine(file);
GXDict.Add(Path.GetFileNameWithoutExtension(s), GV.C_Game1.Content.Load<Texture2D>(subD + "\\" + file));
}
}
}
My error is because subD is, for example, "........\Happy WorkerContent\gfx\level entities\terrains", but Content.Load expects "gfx\level entities\terrains".
I could do something like subD.Substring(32), but this seems messy, especially if I rename any folders or anything later (and may not work in the published version?). Is there a good way to say "I only want the part of the file which is after the "Happy WorkerContent" directory?
You could write a method to return the text following a particular target string.
Then if you needed to search for a different string, you'd just need to pass a different target string to the method.
For example:
// Returns the contents of text following the target string,
// or "" if the target string wasn't found.
public static string ContentAfter(string text, string target)
{
int index = text.IndexOf(target);
if (index >= 0)
return text.Substring(index + target.Length);
else
return "";
}
Then you'd call it like:
string test = "..\\..\\..\\..\\Happy WorkerContent\\gfx\\whatever";
string target = "\\Happy WorkerContent\\";
string following = ContentAfter(test, target);
That wouldn't work so great if you had two strings matching the target string in the text. The method would return all the text after the first match, which would include the second target string of course.

How do I retrieve the value of a string from a list of .cs files?

I have a list of .cs files, each of which contain a string commandID. I need to retrieve the value of this string.
How do I implement this search and retrieve value mechanism in C#?
//Sample code to list all .cs files within a directory
string[] filePaths = Directory.GetFiles(#"c:\MyDir\", "*.cs");
// Sample code to read 1 file.
// Read each line of the file into a string array. Each element
// of the array is one line of the file.
string[] lines = System.IO.File.ReadAllLines(#"C:\Users\Public\TestFolder\file1.cs");
// Display the file contents by using a foreach loop.
foreach (string line in lines)
{
// INSERT YOUR SEARCH LOGIC HERE
}
I am assuming that, there is some string named CommandId in your .Cs files in your project and you are trying to get the value of it because you donot want to manually go to each file and get its value.
Follow the following
1- Paste all the .CS files in a separate folder.
2- Use FileSytem to get all the files in that folder
3- Use stream reader to get the text in the .cs files
4- compare each line in the file with the text you want to find.
5- If the string matches, the save it somewhere like XML or another text file.
6- Read the next file and Go back to step 3.
Finally got the ID out of it :)
let's say you have found the line you want, so I get the ID out of the line like :
string line = "while(i<10){CommandID = 15852; i+=1;}";
//I've put a complicated code in the string to make you sure
var rightSideOfAssignment = line.Split(new string[] {"CommandID"}, StringSplitOptions.RemoveEmptyEntries)[1];
int val = 0,temp;
bool hasAlreadyStartedFetchingNumbers= false;
foreach (char ch in rightSideOfAssignment) //iterate each charachter
{
if (int.TryParse(ch.ToString(), out temp)) //if ch is a number
{
foundFirstInteger = true;
val *= 10;
val += temp;
}
else
{
if (hasAlreadyStartedFetchingNumbers)
break;
//If you don't check this condition, it'll result to 158521
//because after hitting `;` it won't stop searching
}
}
MessageBox.Show(val.ToString()); //shows 15852

Categories

Resources