Deleting an specified string by user in an array? - c#

What i want to do here was getting an string input from the user and if that string input is in the array i want to delete it from the file (all the items in the array is actual files in my computer that got scanned at the start of the program and become one array) is there a way to do that without foreach?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.IO;
using System.Threading;
string typed = null;
string loc = AppDomain.CurrentDomain.BaseDirectory;
if (!Directory.Exists(loc + #"\shortcuts"))
{
Directory.CreateDirectory(loc + #"\shortcuts");
}
string[] directory = Directory.GetFiles(loc + #"\shortcuts");
foreach (var filed in directory)
{
File.Move(filed, filed.ToLowerInvariant());
}
string[] file = Directory.GetFiles(loc + #"\shortcuts").Select(System.IO.Path.GetFileNameWithoutExtension).ToArray();
foreach (string dir in directory)
{
}
if (typed == "exit") System.Environment.Exit(0);
//other ifs here
else if (typed == "rem")
{
//Console.WriteLine("\nNot available at the moment\n");
////add this command
Console.WriteLine("\nWhich program entry do you wish to erase?\n");
typed = Console.ReadLine().ToLower();
if (file.Any(typed.Contains))
{
File.Delete(file.Contains(typed)); //this is the broken part and i don't know how i can get the stings from there
Console.WriteLine("hi");
}
else Console.WriteLine("\n" + typed + " is not in your registered programs list.\n");
}
Expected result was getting rid of the typed program in the folder and actual results was just an error code.

You are storing only the file name in the array, not its complete path or extension. You need to change this, and allow it to store FileName with extension.
string[] file = Directory.GetFiles(loc + #"\shortcuts").Select(System.IO.Path.GetFileName).ToArray();
and then, you need to change the If condition as follows.
if (file.Contains(typed))
{
File.Delete(Path.Combine(loc + #"\shortcuts",typed));
Console.WriteLine("hi");
}
In this Scenario, user would need to input the file name with extension.
If you want the User to input only the filename(without extension, as in your code), then, you could run into a situation where there could be two files with different extension.
"test.jpg"
"test.bmp"
Update
Based on your comment that you cannot store extensions, please find the updated code below. In this scenario, you do not need to change the array. Since you are only storing lnk files, you can append the extension to the file name to complete the path during Path.Combine.
if (file.Contains(typed))
{
File.Delete(Path.Combine(loc , #"shortcuts",$"{typed}.lnk"));
Console.WriteLine("hi");
}

Related

How to handle a case when the hard disk drive letter is not the same when saved it to a text file?

in the constructor :
SaveLoadFiles.LoadFile(textBoxRadarPath, "radarpath.txt");
SaveLoadFiles.LoadFile(textBoxSatellitePath, "satellitepath.txt");
if (textBoxRadarPath.Text != "" || textBoxSatellitePath.Text != "")
{
if(!Directory.Exists(textBoxRadarPath.Text))
{
Directory.CreateDirectory(textBoxRadarPath.Text);
}
if (!Directory.Exists(textBoxSatellitePath.Text))
{
Directory.CreateDirectory(textBoxSatellitePath.Text);
}
btnStart.Enabled = true;
}
else
{
btnStart.Enabled = false;
}
the SaveLoadFiles class
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Weather
{
public class SaveLoadFiles
{
public static void SaveFile(string contentToSave, string fileName)
{
string applicationPath = Path.GetFullPath(System.AppDomain.CurrentDomain.BaseDirectory); // the directory that your program is installed in
string saveFilePath = Path.Combine(applicationPath, fileName);
File.WriteAllText(saveFilePath, contentToSave);
}
public static void LoadFile(TextBox loadTo, string fileName)
{
string applicationPath = Path.GetFullPath(System.AppDomain.CurrentDomain.BaseDirectory); // the directory that your program is installed in
string saveFilePath = Path.Combine(applicationPath, fileName); // add a file name to this path. This is your full file path.
if (File.Exists(saveFilePath))
{
loadTo.Text = File.ReadAllText(saveFilePath);
}
}
}
}
when i used the application before and backed it up on my usb flash drive the second hard drive letter was D i had two hard disks : C and D and the project and the folders were on drive D.
now i backed up the project including the saved files but now my hard disks letters are C and E there is no D
but in the constructor when it's reading the text files the folders in the text files are D:....etc
but it should be E:
I'm checking if the folder exist or not and then if not creating it but it's trying to create the folder on drive D and D is not existing.
You are reading contents of a data file that has a file path that no longer exists.
The solution is to edit those data files: "radarpath.txt" and "satellitepath.txt" to have the proper path.
An application would normally provide a UI for selecting the folder to use, rather than saving a hardcoded path in a datafile. What you could do is use FileDialog to prompt the user for the directories to use if they don't exist.

Get Absolute Path of file in C# from file name [duplicate]

This question already has answers here:
How to get a path to the desktop for current user in C#?
(2 answers)
Closed 3 years ago.
I have a File on my Desktop and I want to get the full Path of the File in my code, should it be on my Desktop or anywhere
My code is looking like this
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GetFullPath
{
class Program
{
static void Main(string[] args)
{
string filename = "eMemoExpenseApproval.docx";
string fullFilePath = Path.Combine(Directory.GetCurrentDirectory(), filename);
Console.Write("Path : " + fullFilePath);
Console.Read();
}
}
}
Rather than get the full path from Desktop it shows the Path from Visual Studio, which is not suppose to be so, but i get this instead
Path : C:\Users\Administrator\Documents\Visual Studio 2017\Projects\GetFullPath\GetFullPath\bin\Debug\eMemoExpenseApproval.docx
Edit:
this works to get the Path of the file on Desktop
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GetFullPath
{
class Program
{
static void Main(string[] args)
{
string filename = "eMemoExpenseApproval.docx";
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string fullFilePath = path +"/"+ filename;
Console.Write("Path : " + fullFilePath);
Console.Read();
}
}
}
Fine but How about other directories?
Directory.GetCurrentDirectory() actually returns the directory in which the application is executed.
If you know that the file is located in your Desktop, you can instead do something like this :
string fullFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop, filename));
As I understand you want to search a limited set of folders for a named file. To do that declare a function like this:
IEnumerable<string> FindInMultipleFolders(string[] folders, string filename)
{
var result = new List<string>();
foreach (var folder in folders)
{
var dirs = Directory.GetFiles(folder, filename);
foreach (String dir in dirs)
{
result.Add(dir);
}
}
return result;
}
And call it with the file name and the folders to search like this:
FindInMultipleFolders(
new string[]
{
Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
#"C:\Some\Other\Folder\I\Would\Like\Searched"
},
"eMemoExpenseApproval.docx");
}
The file might be in multiple folders, so the function returns an IEnumerable<string>. FindInMultipleFolders only searches the passed folders, not subfolders. If you want subfolders to be searched you should add SearchOption.AllDirectories as a third parameter to GetFiles. Then you could search the whole hard drive with:
FindInMultipleFolders(
new string[]
{
#"C:\"
},
"eMemoExpenseApproval.docx");
}

how to check for location is accessible and append to location

I am trying to figure out if any of the below 3 locations are accessible and append to build location,if multiple locations are accessible pick one of them and bail out if none exit,can anyone provide info on how to do this?
1.BIN-LOC-WiFi-FW\loc_proc\bin
2.loc_proc\pkg\cnss_proc\bin
3.loc_proc_ps\package
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aputloader
{
class Program
{
static void Main(string[] args)
{
string buildlocation = #"\\location\builds784\INTEGRATION\LOC.1.2-00028-Z-1";
//check if atleast one of the following folders exist and append to buildlocation
//1.BIN-LOC-WiFi-FW\loc_proc\bin
//2.loc_proc\pkg\cnss_proc\bin
//3.loc_proc_ps\package
//multiple folders exist ,pick one
//none exist ,bail out
}
}
}
Maybe something like this?
if(Directory.Exists("BIN-LOC-WiFi-FW\loc_proc\bin"))
{
// This path is a directory
}
else if(Directory.Exists("loc_proc\pkg\cnss_proc\bin"))
{
// This path is a directory
}
else if(Directory.Exists("loc_proc_ps\package")
{
// This path is a directory
}
else
{
Console.WriteLine("No valid folder exists.");
// Do nothing.
}

Ordering writeline outputs from text file using C# in console

I wonder if you could help me at all. Essentially my program has to scan through a text file and then print the lines. Each line that is printed must be alphabetized also, if possible. I could do with being able to point at any file through cmd rather than automatically pointing it at a specific file and in a specific location.
I have this so far as I wanted to get things working in a basic form.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Program
{
class Program
{
static void Main(string[] args)
{
String line;
try
{
//We Have to pass the file path and packages.txt filename to the StreamReader constructor
StreamReader sr = new StreamReader("D:\\Users\\James\\Desktop\\packages.txt");
//Instruction to read the first line of text
line = sr.ReadLine();
//Further Instruction is to to read until you reach end of file
while (line != null)
{
//Instruction to write the line to console window
Console.WriteLine(line);
//The read the next line
line = sr.ReadLine();
}
//Finally close the file
sr.Close();
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Executing finally block.");
}
}
}
}
I hope you guys can help me, I am very rusty!
My thoughts were to convert the string into an char array? then modify and sort using array.sort method.
OK guys. On your advice I have made a few changes. I get an exception thrown at me now as we are trying to get it to accept an argument in order for us to point it at any text file, not a specific one.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Program
{
class Program
{
static void Main (params string[] args)
{
string PathToFile = args[1];
string TargetPackages = args[2];
try
{
string[] textLines = File.ReadAllLines(PathToFile);
List<string> results = new List<string>();
foreach (string line in textLines)
{
if (line.Contains(TargetPackages))
{
results.Add(line);
}
Console.WriteLine(results);
}
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Executing finally block.");
}
}
}
}
If you just want to sort by the first word and output, you need to read all the lines into memory (I hope your file isn't too large), sort the lines, and then write them back out.
There are many ways to do all that. The File class has some helper functions that make reading and writing text files line-by-line very simple, and LINQ's OrderBy method makes quick work of sorting things.
File.WriteAllLines(
outputFileName,
File.ReadLines(inputFileName).OrderBy(line => line));
See File.WriteAllLines and File.ReadLines for information on how they work.
If you want to load each line, sort the first word, and then re-output the line:
File.WriteAllLines(
outputFileName,
File.ReadLines(inputFileName)
.Select(line =>
{
var splits = line.Split(new [] {' '}};
var firstWord = new string(splits[0].OrderBy(c => c));
var newLine = firstWord + line.Substring(firstWord.Length);
return newLine;
}));
Note that this loads and processes one line at a time, so you don't have to hold the entire file in memory.
You should be better off by reading all lines at once and then looking at each line separately, like this:
List<string> allLines = System.IO.File.ReadLines(pathToFile).ToList();
allLines = allLines.OrderBy(line => line).ToList(); //this orders alphabetically all your lines
foreach (string line in allLines)
{
Console.WriteLine(line);
}
This will print all the lines in the file ordered alphabetically.
You can also parametrize the path by using the args parameter you receive when opening the application:
CMD> pathToYourExe.exe path1 path2 path3
You can mock this by using the DEBUG arguments in the project's Debug menu

Can I add date/time to outputted filename in C# file.writeallbytes

I am writing an errorlog to to file in the same directory the script exists. Id like to potentially create a new folder as it writes as well as add date/time to the filenames so they 2nd doesnt save over the first.
Here is what I have so far:
File.WriteAllBytes("ErrorLog.txt")
Thanks!
You can create a valid Windows file name with DateTime in it like this:
string filename = "ErrorLogFolder" + DateTime.Now.ToString("dd-MM-yyyy_hh-mm-ss") + ".txt";
Take a look at this sample code for naming a file
using System;
using System.IO;
class Program
{
static void Main()
{
//
// Write file containing the date with BIN extension
//
string n = string.Format("text-{0:yyyy-MM-dd_hh-mm-ss-tt}.bin",
DateTime.Now);
File.WriteAllText(n, "aaa");
}
}

Categories