Adding a number suffix when creating folder in C# - c#

I'm trying to handle if the folder i want to create is already exist .. to add a number to folder name .. like windows explorer .. e.g(New Folder , New Folder 1 , New Folder 2 ..)
how can i do it recursively
i know this code is wrong.
how can i fix or maybe change the code below to solve the problem ?
int i = 0;
private void NewFolder(string path)
{
string name = "\\New Folder";
if (Directory.Exists(path + name))
{
i++;
NewFolder(path + name +" "+ i);
}
Directory.CreateDirectory(path + name);
}

For this, you don't need recursion, but instead should look to an iterative solution:
private void NewFolder(string path) {
string name = #"\New Folder";
string current = name;
int i = 1;
while (Directory.Exists(Path.Combine(path, current))) {
i++;
current = String.Format("{0}{1}", name, i);
}
Directory.CreateDirectory(Path.Combine(path, current));
}

private void NewFolder(string path)
{
string name = #"\New Folder";
string current = name;
int i = 0;
while (Directory.Exists(path + current))
{
i++;
current = String.Format("{0} {1}", name, i);
}
Directory.CreateDirectory(path + current);
}
credit for #JaredPar

The simpliest way to do it is:
public static void ebfFolderCreate(Object s1)
{
DirectoryInfo di = new DirectoryInfo(s1.ToString());
if (di.Parent != null && !di.Exists)
{
ebfFolderCreate(di.Parent.FullName);
}
if (!di.Exists)
{
di.Create();
di.Refresh();
}
}

You can use this DirectoryInfo extender:
public static class DirectoryInfoExtender
{
public static void CreateDirectory(this DirectoryInfo instance)
{
if (instance.Parent != null)
{
CreateDirectory(instance.Parent);
}
if (!instance.Exists)
{
instance.Create();
}
}
}

Related

C#: Cannot get 100% score for "Path" www.testdome.com/questions/c-sharp/path/12280?visibility=1

Practice on the C# question on the testdome https://www.testdome.com/questions/c-sharp/path/12280?visibility=1. I only get 75% score. Could someone help me to get 100% score? Code attached below
using System.Collections.Generic;
public class Path {
public string CurrentPath { get; private set; }
public Path(string path) {
this.CurrentPath = path;
}
public void Cd(string newPath) {
//absolute path
if (newPath.StartsWith("/")) {
CurrentPath = newPath;
} else if (newPath.Contains("../")) {
var pathList = new LinkedList<string>(CurrentPath.Split('/'));
var newPathList = newPath.Split('/');
foreach (var item in newPathList) {
if (item == "..") {
if (pathList.Count > 0)
pathList.RemoveLast();
} else {
pathList.AddLast(item);
}
}
CurrentPath = string.Join("/", pathList);
if (!CurrentPath.StartsWith("/"))
CurrentPath = "/" + CurrentPath;
} else {
CurrentPath += "/" + newPath;
}
}
}
Your code misses test cases when .. appears at the end of the path, e.g.
some-dir/dir/..
Your code prepends / and returns the path without further processing, because the string does not contain "../" search string. Removing forward slash from that string fixes this problem.

C# LINQ statement

I have two lists; List<int> numList has identifier number as its elements, and List<string> filePaths has path to file that needs to be analyzed as its elements. I want to filter filePaths based on the numList; that is, I only want to select the filePaths whose file names have the identifier number that is present in the numList.
For example, filePaths has
C:/test/1.test.xlsx
C:/test/2.test.xlsx
C:/test/3.test.xlsx
C:/test/4.test.xlsx
and, numList has
1
2
In this case, I want to construct LINQ statement to only get
C:/test/1.test.xlsx
C:/test/2.test.xlsx
I tried
for(int i = 0; i < numList.Count; i++)
{
filePaths = filePaths.Where(f => Convert.ToInt32(GetNumberFromString(Path.GetFileName(f))) == numList[i]).ToList();
}
And this is GetNumberFromString Helper Method
// Find number in the string
private string GetNumberFromString(string value)
{
int number;
string resultString = Regex.Match(value, #"\d+").Value;
if (Int32.TryParse(resultString, out number))
{
return resultString;
}
else
{
throw new Exception(String.Format("No number present in the file {0}", value));
}
}
I think this will work, but is there more elegant/efficient way of achieving this?
You can do it with a one-liner:
var filteredFilePaths = filePaths.Where(x => numList.Contains(GetNumberFromString(x));
I'd do it like this. The test method assumes that all the files in directory have appropriately formatted names. If that's not a reasonable assumption, it's easy enough to fix.
This is overkill, however, if you only ever care about the "file number" in one place.
public class TestClass
{
public static void TestMethod(String directory)
{
var files = System.IO.Directory.GetFiles(directory).Select(f => new FileInfo(f)).ToList();
var numList = new[] { 1, 2 };
var oneAndTwo = files.Where(fi => numList.Contains(fi.FileNumber)).ToList();
}
}
public class FileInfo
{
public FileInfo()
{
}
public FileInfo(String path)
{
Path = path;
}
public int FileNumber { get; private set; }
private string _path;
public String Path
{
get { return _path; }
set
{
_path = value;
FileNumber = GetNumberFromFileName(_path);
}
}
public static int GetNumberFromFileName(string path)
{
int number;
var fileName = System.IO.Path.GetFileName(path);
string resultString = Regex.Match(fileName, #"\d+").Value;
if (Int32.TryParse(resultString, out number))
{
return number;
}
else
{
throw new Exception(String.Format("No number present in the file {0}", path ?? "(null)"));
}
}
}
A stand-alone One-liner using a Join :
var result = filePaths.Select(x => new { Filename = Path.GetFileName(x), x })
.Join(numList, x => Regex.Match(x.Filename, "^([0-9]+)").Value,
y => y.ToString(),
(x, y) => x.x);

C# custom object in combobox

I am relatively new to C# (WinForms), and had a question regarding combo boxes. I have a combo box of Reviewer objects (it is a custom class with an overridden ToString method) and am currently attempting to go through all the checked items and use them to generate a setup file.
Here is how the combo box is populated (populated on form load). Parameters is just a collection of linked lists and parsing code.
for (int i = 0; i < parameters.GetUsers().Count; i++)
{
UserList.Items.Add(parameters.GetUsersArray()[i], parameters.GetUsersArray()[i].isSelected());
}
Here is how I am trying to read it. setup is a StringBuilder. The problem is that GetID is not defined. Does the add function above cast the Reviewer object to a Object object? It looks a little funny since it creates a file fed into a Perl script. A sample desired output line looks like this: inspector0 => "chg0306",
for (int i = 0; i < UserList.CheckedItems.Count; i++)
{
setup.AppendLine("inspector" + i.ToString() + " => \t \"" +
UserList.CheckedItems[i].GetID() + "\",");
}
Here is the users class: (Sample User is ID = aaa0000 name: Bob Joe)
public class Reviewer
{
private string name;
private string id;
private bool selected;
public Reviewer(string newName, string newID, bool newSelected)
{
name = newName;
id = newID;
selected = newSelected;
}
public string GetName()
{
return name;
}
public override string ToString()
{
//string retVal = new string(' ', id.Length + name.Length + 1);
string retVal = id + '\t' + name;
return retVal;
}
public string GetID()
{
return id;
}
public bool isSelected()
{
return selected;
}
}
For posterity, here is the Parameters class:
public class ParameterLists
{
public ParameterLists()
{
projects = new LinkedList<string>();
reviewers = new LinkedList<Reviewer>();
}
public enum FileContents {
PROJECT_LIST,
USERS_LIST,
}
public LinkedList<Reviewer> GetUsers()
{
return reviewers;
}
public LinkedList<string> GetProjects()
{
return projects;
}
public Reviewer[] GetUsersArray()
{
Reviewer[] userArray = new Reviewer[reviewers.Count];
reviewers.CopyTo(userArray, 0);
return userArray;
}
public string[] GetProjectsArray()
{
String[] projectArray = new String[projects.Count];
projects.CopyTo(projectArray, 0);
return projectArray;
}
public void LoadParameters(string fileName)
{
//Reads the parameters from the input file.
}
private void CreateDefaultFile(string fileName)
{
// Create the file from the defaultfile , if it exists.
// Otherwise create a blank default file.
}
private LinkedList <string> projects;
private LinkedList <Reviewer> reviewers;
}
I am probably missing something simple, coming from embedded C++. Any help would be appreciated.
You have to cast that object:
((Reviewer)UserList.CheckedItems[i]).GetID()

How to update and delete a specific line from a text file in C# windows form [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am new in using file handler in c#. I have done insert and search. Please help me how can I do update and delete using this following code.
UI part::
private void btnAdd1_Click(object sender, EventArgs e)
{
StudentManager sm = new StudentManager();
sm.AddStudent(textName.Text,textId.Text,textDpt.Text,textSem.Text);
}
public void btnSearch1_Click(object sender, EventArgs e)
{
StudentManager sm = new StudentManager();
Student s = sm.FindStudent(textId.Text);
if (s != null)
{
this.textName.Text = s.GetName();
this.textId.Text = s.ID;
this.textDpt.Text = s.Department;
this.textSem.Text = s.GetSEM();
}
}
validation::
string id = String.Empty;
public void SetName(string name)
{
if(!String.IsNullOrEmpty(name))
{
this.name = name;
}
}
public string ID
{
get { return id; }
set { id = value; }
}
string department = String.Empty;
public string Department
{
get { return department; }
set { department = value; }
}
string SEM= String.Empty;
public void SetSEM(string sem)
{
if (!String.IsNullOrEmpty(sem))
{
this.SEM = sem;
}
}
public string GetSEM()
{
return this.SEM;
}
public String GetName()
{
return this.name;
}
}
studentManager::
class StudentManager
{
ArrayList students;
const string FILENAME = #"d:\students.txt";
public StudentManager()
{
SetStudentList();
}
private void SetStudentList()
{
if (students == null)
{
//create a file handler
FileHandler sfh = new FileHandler();
//initialize the teacher list object
students = new ArrayList();
//Now read all the lines from the teacher.txt
//each line represent a teacher
string[] studentfromfile = sfh.getAllLines(#FILENAME);
int totalstudents = studentfromfile.Length;
//go through each teacher and create teacher object to add it to the teacher list.
for (int i = 0; i < totalstudents; i++)
{
string studentinfo = studentfromfile[i];
string[] studentinfobroken = studentinfo.Split(new char[] { ',' });
if (studentinfobroken.Length == 4)
{
//this part is being duplicated - can think how?
Student s = new Student();
s.SetName(studentinfobroken[0]);
s.ID= studentinfobroken[1];
s.Department = studentinfobroken[2];
s.SetSEM(studentinfobroken[3]);
this.students.Add(s);
}
}
}
}
public void AddStudent(string fullname, string ID, string dept,string Semester )
{
Student s = new Student();
s.SetName(fullname);
s.ID = ID;
s.Department = dept;
s.SetSEM(Semester);
this.students.Add(s);
FileHandler sfh = new FileHandler();
string studentInfo = Environment.NewLine + s.GetName() + "," + s.ID + "," + s.Department + "," + s.GetSEM();
sfh.AddLine(#FILENAME, studentInfo);
}
public Student FindStudent(string ID)
{
foreach (Student s in students)
{
if (s.ID.Equals(ID))
{
return s;
}
}
return null;
}
class FileHandler
{
public String[] getAllLines(string fileName)
{
try
{
String[] lines = File.ReadAllLines(#fileName);
return lines;
}
catch (Exception e)
{
throw e;
}
}
public String GetAllText(string fileName)
{
try
{
String content = File.ReadAllText(#fileName);
return content;
}
catch (Exception e)
{
throw e;
}
}
public void AddLine(string filename, string line)
{
StreamWriter sr = null;
try
{
sr = new StreamWriter(#filename, true);//true for append
sr.WriteLine(line);
}
catch (Exception e)
{
throw e;
}
finally
{
sr.Close();
}
}
Ok I've looked over your code and it looks as though you update your textfile after every little thing you do which is the wrong approach.. (If I'm wrong then please reduce the code in your example to make it easier to read!)
What you should be trying to do is when your program loads, load the students from the file into a list of Students. Then whilst your program persists you should use this list wherever you need it. When you are ready to close your program, then you write it back to the file.
One advantage of this way, other than the obvious efficiency and ease of use, is that changes can be cancelled without your only copy of students being destroyed.
e.g
studentList.Remove(student) - Remove from list
studentList.Add(student) - add
studentList.Where(x => x.Name = "Joe"); - Filter
Update
studentfromfile[5] = "updated line";
File.WriteAllLines(FILENAME, studentfromfile);
Delete
studentfromfile[5] = String.Empty;
studentfromfile = studentfromfile.Where(x => !String.IsNullOrEmpty(x)).ToArray();
File.WriteAllLines(FILENAME, studentfromfile);
There are better ways of doing this such as using a collection as Sayse recommends. You shouldn't use ArrayLists, they're not required if you're creating a project that targets .Net 2.0 and above (use List), and you shouldn't throw exceptions like that because you're losing the stacktrace. Use
try
{
String content = File.ReadAllText(#fileName);
return content;
}
catch (Exception e)
{
throw; //not throw e;
}

c# How to write to a ini file [duplicate]

This question already has answers here:
Reading/writing an INI file
(17 answers)
Closed 9 years ago.
I would like to know how i should write text to a ini file. The reading of the file is already done. Now i just have to know how to write to the file.
It should look like this when its in the INI file:
[H83052_md7]
Description=H83048 processor mode 7
BootFile=kernel_52.md7
Extension=a20
If you would like to see how i read from the file ask me for the source code please because i could not figure out how i should do this.
I write it like this:
namespace Flashloader
{
class Controllerlist : List<Controller>
{
public Controllerlist FromIniFile()
{
StringList input = new StringList().FromFile("Controllers.ini");
Controller controller = null;
foreach (var item in input)
{
String line = item.Trim();
if (line.StartsWith("[") && line.EndsWith("]"))
{
String name = line.Substring(1, line.Length - 2);
controller = new Controller(name);
Add(controller);
}
else if (controller != null)
{
int index = line.IndexOf('=');
if (index < 0)
continue;
String key = line.Substring(0, index).Trim();
String value = line.Substring(index + 1).Trim();
if (Utils.EqualsIgnoreCase(key, "Description"))
controller.Description = value;
else if (Utils.EqualsIgnoreCase(key, "Bootfile"))
controller.Bootfile = value;
else if (Utils.EqualsIgnoreCase(key, "Extension"))
controller.Extension = value;
}
}
return this;
}
public Controller FindByName(String name)
{
foreach (var item in this)
if (Utils.EqualsIgnoreCase(item.Name, name))
return item;
return null;
}
}
}
Try this class:
public class IniFile
{
public string path;
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section,
string key,string val,string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section,
string key,string def, StringBuilder retVal,
int size,string filePath);
public IniFile(string INIPath)
{
path = INIPath;
}
public void IniWriteValue(string Section,string Key,string Value)
{
WritePrivateProfileString(Section,Key,Value,this.path);
}
public string IniReadValue(string Section,string Key)
{
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(Section,Key,"",temp,255, this.path);
return temp.ToString();
}
}
This is the best solution to write/read INi file. http://www.blackwasp.co.uk/IniFile.aspx

Categories

Resources