Can you convert an IEnumerated string to a normal string? - c#

I'm using this to find and replace exe files
public static void Replace()
{
string origFile = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "/Virus.exe"; //original file
IEnumerable<string> toOverwrite = EnumerateFiles(); //newly enumarated files
string backupFile = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "/temp"; //backup file (temporary)
File.Replace (origFile, toOverwrite, backupFile); //replaces files
}
public static IEnumerable<string> EnumerateFiles()
{
string pathToSearch = Environment.GetFolderPath (Environment.SpecialFolder.DesktopDirectory); //Sets search directory to the desktop
IEnumerable<string> exeFiles = Directory.EnumerateFiles (pathToSearch); //Searches desktop for all exe files
return exeFiles; //Returns enumerated list of files
}
but when I do the File.Replace method, it tells me that I can't convert IEnumerable String to a normal String. How can I change the string type without changing the value?

Thats beacuse IEnumeable is a bunch of strings. File.Replace wants one string. What you are trying to do doesnt make sense. I suspect you need to loop over the files in toOverwrite collection
public static void Replace()
{
string origFile = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "/Virus.exe"; //original file
IEnumerable<string> toOverwrite = EnumerateFiles(); //newly enumarated files
string backupFile = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "/temp"; //backup file (temporary)
foreach(var file in toOverwrite)
{
File.Replace (origFile, file, backupFile); //replaces files
}
}

Related

Renaming copy of multiple files in C# in a uniform format

I'm working with C# in ASP.net framework. I need to make a copy of files and save them.
File.Copy("fileFirst.txt", "fileSecond.txt"); seems to work for that.
However I have multiple files and I need to do this for every single file. Instead of having to type the names for every single file how can I simply have a copy of the file such that it has the original filename with a -new appended on it's back.
Original file: fileFirst.txt
Copy of the file: fileFirst-new.txt
NOTE: It has to to do this for as many files as I have and not just one.
This code lists all the files in a directory and copies them to the same folder but with a different name.
private static void RenameDirectoryFiles()
{
string pathfile = #"M:\_downloads\";
string[] filePaths = Directory.GetFiles(pathfile);
foreach (string filePath in filePaths)
{
try
{
string dire = Path.GetDirectoryName(filePath);
string name = Path.GetFileNameWithoutExtension(filePath);
string exte = Path.GetExtension(filePath);
File.Copy($"{filePath}", $"{pathfile}\\{name}-New{exte}");
}
catch (Exception e)
{
Console.WriteLine("Error File Copy");
}
}
}

removing file extension and location from list box

Im making a mp3 player in c# and im using a autoload function and it works perfectly to load and play, but the "problem" in in the list box where the .mp3 files are displayed. it shows the file directory and file extension like this:
C:\Users\Felix\Documents\songs_here\list_1\Admiral P - Engle.mp3
and insteed of that i would like it to show:
Admiral P - Engel
is this possible and how to i do it? the file load code is:
private void PopulateListBox1(string folder)
{
string[] files = Directory.GetFiles(folder);
foreach (string file in files)
listBox1.Items.Add(file);
}
PopulateListBox1(dir1);
Thanks in advance!!
You can use Path.GetFileNameWithoutExtension.
Path.GetFileNameWithoutExtension Method (String)
Returns the file name of the specified path string without the extension.
For example:
Path.GetFileNameWithoutExtension("C:\Users\...\songs_here\list_1\Admiral P - Engle.mp3");
Would return:
Admiral P - Engle
Update:
I'm assuming from your comment that you want to display the file name but still have a reference to the path to the file to pass to your player.
You'll need to create your own class to hold the mp3 file name and path like this:
public class MusicFile
{
public string Path;
public string FileName;
public override string ToString()
{
return FileName;
}
}
private void PopulateListBox1(string folder)
{
string[] files = Directory.GetFiles(folder);
foreach (string file in files)
{
var music = new MusicFile
{
Path = file,
FileName = Path.GetFileNameWithoutExtension(file)
};
listBox1.Items.Add(music);
}
}
This shows how to loop through each item and get the path, but you could also use events such as SelectedIndexChanged depending on your needs.
foreach (var item in listBox1.Items)
{
var filepath = ((MusicFile)item).Path; // Shows the full path, pass this to the player
}
Using Linq one line code
private void PopulateListBox1(string folder)
{
listBox1.DataSource =Directory.GetFiles(folder).Select(x => Path.GetFileNameWithoutExtension(x)).ToList();
}
as the file naming pattern is the same, first you might want to check file extension with a string split on dot character on every file entry, then for each file if it is mp3 extension , split an pop the last word

How to crop string from multiple txt files?

I have thousands of .log files and I need to find some string in all of the files.
I will explain with example: on all of .log files I have string calles "AAA" and after that string I have anumber that can be diffrenet from one log file to other log file. I know how to search the AAA string. what I dont knew is how to crop only the string number that is after the AAA string.
update:
the .log file containes a lot of lines.
on the .log file I have only 1 line that contains the string "A12A".
after that line I have anumber (for examle: 5465).
what I need is to extract the number after the A12A.
note: there is a spacing between the A12A to the 5465 string number.
example:
.log file : "assddsf dfdfsd dfd A12A 5465 dffdsfsdf dfdf dfdf "
what I need to extract: 5465.
what I have so far is:
// Modify this path as necessary.
string startFolder = #"c:\program files\Microsoft Visual Studio 9.0\";
// Take a snapshot of the file system.
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(startFolder);
// This method assumes that the application has discovery permissions
// for all folders under the specified path.
IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
string searchTerm = #"Visual Studio";
// Search the contents of each file.
// A regular expression created with the RegEx class
// could be used instead of the Contains method.
// queryMatchingFiles is an IEnumerable<string>.
var queryMatchingFiles =
from file in fileList
where file.Extension == ".htm"
let fileText = GetFileText(file.FullName)
where fileText.Contains(searchTerm)
select file.FullName;
// Execute the query.
Console.WriteLine("The term \"{0}\" was found in:", searchTerm);
foreach (string filename in queryMatchingFiles)
{
Console.WriteLine(filename);
}
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
// Read the contents of the file.
static string GetFileText(string name)
{
string fileContents = String.Empty;
// If the file has been deleted since we took
// the snapshot, ignore it and return the empty string.
if (System.IO.File.Exists(name))
{
fileContents = System.IO.File.ReadAllText(name);
}
return fileContents;
}
I would recommend the following code for doing the search itself:
private static readonly string _SearchPattern = "A12A";
private static readonly Regex _NumberExtractor = new Regex(#"\d+");
private static IEnumerable<Tuple<String, int>> FindMatches()
{
var startFolder = #"D:\";
var filePattern = #"*.htm";
var matchingFiles = Directory.EnumerateFiles(startFolder, filePattern, SearchOption.AllDirectories);
foreach (var file in matchingFiles)
{
// What encoding do your files use?
var lines = File.ReadLines(file, Encoding.UTF8);
foreach (var line in lines)
{
int number;
if (TryGetNumber(line, out number))
{
yield return Tuple.Create(file, number);
// Stop searching that file and continue with the next one.
break;
}
}
}
}
private static bool TryGetNumber(string line, out int number)
{
number = 0;
// Should casing be ignored??
var index = line.IndexOf(_SearchPattern, StringComparison.InvariantCultureIgnoreCase);
if (index >= 0)
{
var numberRaw = line.Substring(index + _SearchPattern.Length);
var match = _NumberExtractor.Match(numberRaw);
return Int32.TryParse(match.Value, out number);
}
return false;
}
The reasons are that when doing I/O operations, the drive itself is normally the bottleneck. So it doesn't make sense to do anything in parallel or to read a lot of data from the file into memory without using it.
By using the Directory.EnumerateFiles method the drive will be searched lazily and you can start examining the first file, right after it was found. The same holds true for the File.ReadLines method. It lazily iterates through the file while you are searching for your pattern.
Through this approach you should get a maximum speed (depending on your hard-drive performance) cause it makes the minimum needed I/O calls needed to get the files and content to your code.

How to get files with desired name in C# using Directory.Getfile?

I am trying to obtain a file of name "fileName.wav" from the directory whose path has been specified im not able to get the desired function .. any help in this regard is appreciated.
static void Main(string[] args)
{
string[] fileEntries = Directory.GetFiles(
#"D:\project\Benten_lat\BentenPj_000_20141124_final\Testing\DPCPlus\Ref\Generated_Ref_Outputs_MSVS", "*.wav");
foreach (string fileName in fileEntries)
{
string[] fileEntries1 = Directory.GetFiles(
#"D:\project\older versions\dpc_latest\Testing\DPCPlus\input");
foreach (string fileName1 in fileEntries1)
{
Console.WriteLine(Path.GetFileName(fileName1));
}
}
}
This Code will search for all .xml extension files with matches abCd name from C:\\SomeDir\\ folder.
string cCId ="abCd";
DirectoryInfo di = new DirectoryInfo("C:\\SomeDir\\");
FileInfo[] orderFiles = di.GetFiles("*" + cCId + "*.xml", SearchOption.TopDirectoryOnly);
You should change this code according to your needs.
Hope this helps you.
If you want to extract name and extension from a file-path, you can use following code:
string result = Path.GetFileName(yourFilePath); // result will be filename.wav
You can not use GetFiles method for a file path!
Directory.GetFiles(#"D:\project\Benten_lat\BentenPj_000_20141124_final\Testing\DPCPlus\Ref\Generated_Ref_Outputs_MSVS\filename.wav") //Error
The input for this method should be a directory!
Assumptions based on your question (please correct me if I am wrong):
You know the folder (e.g. the user entered it)
You know the file name (e.g. it is hard coded because it must be the same always)
In this case you do not really need to search the file.
Solution:
string folderPath = #"D:\somewhere";
string fileName = "file.wav";
string filePath = Path.Combine(folderPath, fileName);
if (File.Exists(filePath))
{
// continue reading the file, etc.
}
else
{
// handle file not found
}

C# check driver for file types followed by action

So basically i am making an app that will sync file types is different ways, I want to search the whole of a logical Drive for example C:\ for all text files.How ever once i find all the text files i want to apply an action for example move all text files to one location or email all text files to the users email.
I have found this code from a past Stack overflow post
public List<string> Search()
{
var files = new List<string>();
foreach (DriveInfo d in DriveInfo.GetDrives().Where(x => x.IsReady))
{
try
{
files.AddRange(Directory.GetFiles(d.RootDirectory.FullName, "*.txt", SearchOption.AllDirectories));
}
catch(Exception e)
{
Logger.Log(e.Message); // Log it and move on
}
}
return files;
}
But what i want to know is how do i do somthing when i find the files ?
The code you posted looks like it should fill List<string> files with strings representing names of files that have a .txt extension.
It should be as simple as iterating over the value returned from the function and doing as you please with them.
This code should (untested) check for a target directory, create it if it doesn't exist, and then copy each file returned from Search() to the target path.
List<string> results = Search();
String targetPath = "C:/TargetDirectory/";
if (!System.IO.Directory.Exists(targetPath))
System.IO.Directory.CreateDirectory(targetPath);
foreach (string aFileStr in results)
{
String sourceFile = aFileStr;
String destFile = Path.Combine(targetPath, Path.GetFileName(aFileStr));
System.IO.File.Copy(sourceFile, destFile, true);
}
You would do a foreach on the list of strings that that function returns.
I'm not quite sure if I understand you correctly. If you just want to know how to process your filelist, you could for instance do the following:
var filelist = Search();
foreach (var s in filelist) {
string fn = System.IO.Path.GetFileName(s);
string dest = System.IO.Path.Combine("c:\\tmp", fn);
System.IO.File.Copy(s, dest, true);
}
which will copy all files in filelist to c:\tmp and overwrite files with equal filename.

Categories

Resources