I've tested the code and the directory gets the correct input, but for some reason it can't find it. Is there something I'm missing why I can't find any directory?
Here is my code pretty simplistic as of right now.
public partial class Form1 : Form
{
string fileName;
string dirName;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
dirName = textBox1.Text;
fileName = textBox2.Text;
if (System.IO.Directory.Exists(dirName))
{
if (System.IO.File.Exists(fileName))
{
System.IO.File.Delete(fileName);
}
else
{
MessageBox.Show("Invalid Directory or File Name");
}
}
}
That's because I guess you're passing the directory path by an input control in this way "C:/examplePath/" and it should be declared in this way "C:\\examplePath" because the escape characters, and probably you'll get another error further because when you're asking for a file's existence, you must to declare it concatenating directory path plus filename (and its extension).
so the final string should be like this "c:\\exampleDir\\examplefile.ext"
or simply you should try:
dirName = string.Format("#{0}", textBox1.Text);
fullPathFile = string.Format("{0}/{1}", dirName, textBox2.Text);
And then you use "fullPathFile" instead of "fileName" variable.
Don't forget to debug your application for making sure what's the string values.
Based on your code, it appears fileName and dirName come from two different textbox controls. And you also dont do any sort of combining the file path (or so it appears). So when you call Directory.Exists() it makes sense that this would work but it can't find the file. When you use File.Exists() you need to pass in not only the file name but also the directory where its located. To do this use the Path.Combine() method.
if (System.IO.Directory.Exists(dirName))
{
string filePath = System.IO.Path.Combine(dirName, fileName);
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
else
{
MessageBox.Show("Invalid Directory or File Name");
}
}
Related
I am having a problem with coding my save-directory. I want it to create a folder called "Ausgabe" (Output) on the current users Desktop, but I do not know how to check if it already exists and if it doesn't then create it.
This is my current code for that part so far:
public partial class Form1 : Form
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
// need some code here
}
What do I add in order to make it do what I want it to do?
You can check if a directory exists using
Directory.Exists(pathToDirectory)
and create a directory using
Directory.CreateDirectory(pathToDirectory)
EDIT In response to your comment:
string directoryPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Ausgabe")
should give you the path to a folder named 'Ausgabe' in the users Desktop-folder.
Just use Directory.CreateDirectory. If the directory exists the method will not create it (in other words it contains a call to Directory.Exists internally)
public partial class Form1 : Form
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
public Form1()
{
string myFolder = Path.Combine(path, "Ausgabe");
Directory.CreateDirectory(myFolder);
}
To use this method you need to add a using System.IO to the top of your Form1.cs file.
I wish also to say that the Desktop is not the most appropriate place to create a directory for your application. There is a proper place provided by the System and it is under the ProgramData enum (CommonApplicationData or ApplicationData)
string path = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
As per this doc, the Directory.CreateDirectory Method (String) will
Creates all directories and subdirectories in the specified path
unless they already exist.
So it is fine to use like this:
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string desktopFolder = Path.Combine(path, "New Folder");
Directory.CreateDirectory(desktopFolder);
You can use the Directory.Exists() method: https://msdn.microsoft.com/en-us/library/system.io.directory.exists(v=vs.110).aspx
Your code would propebly look something like this:
public static void Main()
{
// Specify the directory you want to manipulate.
string path = #"c:\MyDir";
try
{
// Determine whether the directory exists.
if (Directory.Exists(path))
{
Console.WriteLine("That path exists already.");
return;
}
// Try to create the directory.
DirectoryInfo di = Directory.CreateDirectory(path);
Console.WriteLine("The directory was created successfully at {0}.", Directory.GetCreationTime(path));
// Delete the directory.
di.Delete();
Console.WriteLine("The directory was deleted successfully.");
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
finally {}
}
I have had a recent issue so here is my solution,
I had to find the deployed directory
var deployedDir = Assembly.GetEntryAssembly().CodeBase;
deployedDir = Path.GetDirectoryName(deployedDir);
deployedDir = deployedDir.Replace("file:\\", "");
var pathToDirectory= Path.Combine(deployedDir, "YourFileName");
Then do what the above answers show and create the directory if it doesnt exist,
Directory.CreateDirectory(pathToDirectory)
How to get the string in the button text?
private void btn_open_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
ReadCSV(openFileDialog1.FileName);
btn_open.Text = "filename here";
string targetdirectory = "D:\\Projects";
string filename = Path.GetFileNameWithoutExtension(target directory);
}
thanks for your help
When you select a file using OpenFileDialog, the OpenFileDialog.FileName contains the full path of the file selected.
Path.GetFileNameWithoutExtension() does just that, getting the file name without extension. However you need to pass an actual file path, not a directory. If you pass a directory path, it will simply retrieve the innermost directory name which is not what your desired outcome.
So what you should do is;
Get file name from OpenFileDialog.
Pass that to the Path.GetFileNameWithoutExtension() method.
Set the resulting string as the button text.
Also the correct usage of ShowDialog() is to check the return value; it returns true if the user clicked OK button, and false otherwise.
if(openFileDialog1.ShowDialog() == true)
{
string file = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
btn_open.Text = file;
}
Can i get the full path from a filename such as get the full directory path from test.txt, Or is there a way i can save it
The reason im asking this is im making a application like Notepad++ some of you may of heard of it. When changing the tab control tab I want the form's text to be the full directory while the tabs text is just filename.format
My so far code
private void tabControl1_TabIndexChanged(object sender, EventArgs e)
{
if (tabControl1.SelectedTab.Text.StartsWith("New"))
{
int count = tabControl1.TabCount - 1;
this.Text = tabControl1.Controls[count].Text + " - My Note 1.0";
}
//It is a directory and i need to make the forms text the path here?
}
You can use System.IO.Path.GetFullPath:
var fullPath = Path.GetFullPath("test.txt");
If you pass in a short file name, it is expanded to a long file name.
If c:\temp\newdir is the current directory, calling GetFullPath on a file name such as test.txt returns c:\temp\newdir\test.txt.
And if you want to get path from that you use System.IO.Path.GetDirectoryName
var path = Path.GetDirectoryName(fullPath)
I think you should probably keep the full path and get the filename from the full path rather than the other way around. The key is to use a type representing a document, and let the tab view that document. If each tab refers to a document, and each document knows its full path, then you can get the short filename from the documents full path.
public class Document
{
public string FullPath { get; set; } // Full path to file, null for unsaved
public string FileName
{
get { return Path.GetFileName(FullPath); }
}
}
When a new tab is focused, get the document for the active tab and set the forms title from the FullPath of the document.
private void tabControl1_TabIndexChanged(object sender, EventArgs e)
{
Document activeDoc = GetDocumentFromActiveTab();
// Update win title with full path of active doc.
this.Text = (activeDoc.FullPath ?? "Unsaved document") + " MyApp" + version;
}
EDIT:
The key here is of course the method GetDocumentFromActiveTab() which isn't shown. You need to implement the data structures that manage your documents, and connects them to tabs. I did not include that in the answer, you need to try yourself. One idea is to make a type representing the entire application state including all tabs and documents.
public class Workspace
{
private Dictionary<SomeTypeOfView, Document> documentsOpenInViews;
// Methods to register a document to a tab, get document for a tab
// remove tab+document when tab is closed etc.
}
// not sure if this is what you want
say your filename with path is
string strFFL = #"C:\path\filename.format";
Console.WriteLine(System.IO.Path.GetFileName(strFFL)); //->filename.format
Console.WriteLine(System.IO.Path.GetDirectoryName(strFFL)); //-> C:\path
http://msdn.microsoft.com/en-us/library/system.io.path.getfilename(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/system.io.path.getdirectoryname(v=vs.110).aspx
I think this is actually backwards. I think you want to keep a full path to the file and be able to display the filename only on the tab. So I think you want Path.GetDirectory name.
From: http://msdn.microsoft.com/en-us/library/system.io.path.getdirectoryname(v=vs.110).aspx
string filePath = #"C:\MyDir\MySubDir\myfile.ext";
string directoryName;
int i = 0;
while (filePath != null)
{
directoryName = Path.GetDirectoryName(filePath);
Console.WriteLine("GetDirectoryName('{0}') returns '{1}'",
filePath, directoryName);
filePath = directoryName;
if (i == 1)
{
filePath = directoryName + #"\"; // this will preserve the previous path
}
i++;
}
/*
This code produces the following output:
GetDirectoryName('C:\MyDir\MySubDir\myfile.ext') returns 'C:\MyDir\MySubDir'
GetDirectoryName('C:\MyDir\MySubDir') returns 'C:\MyDir'
GetDirectoryName('C:\MyDir\') returns 'C:\MyDir'
GetDirectoryName('C:\MyDir') returns 'C:\'
GetDirectoryName('C:\') returns ''
*/
How can I change the foldername if there exists some other folder with that name?
I tried in the below manner but it didn't work :(
private int ik;
protected void Button1_Click(object sender, EventArgs e)
{
string folderpath = #"C:\Users\nouser\Documents\Visual Studio 2010\WebSites\folders";
string foldername = TextBox1.Text;
string newPath = System.IO.Path.Combine(folderpath, foldername);
if (Directory.Exists(Path.Combine(folderpath, foldername)))
{
foldername = foldername + Convert.ToString(ik);
ik = ik + 1;
}
else
{
System.IO.Directory.CreateDirectory(newPath);
Response.Write("Folder created");
}
}
This code is able to create a new folder but unable to change the folder name from "newfolder" to "newfolder1" if "newfolder" already exists.
I'm assuming you want something where if you try to create a folder named "foo" but a folder named "foo" exist already you want your new folder to be called "foo1"? If so you'll have to detect if the folder exists or not and create a new name for it. You can do something like this
var count = 1;
var originalPath = newPath;
while(Directory.Exists(newPath)){
newPath = originalPath + count;
count++;
}
Directory.CreateDirectory(newPath);
This ensures that your new path doesn't already exist and if it does will ensure you get a unique name for your folder.
In your example I wasn't sure what you were doing with the variable
ik
I think thats where you were trying to create a unique directory, but what happens if you already have a newFolder1 there? This is why you should use a while loop to keep checking
Use system.IO.Directory move
System.IO.Directory.Move("newfolder","newfolder1");
For more information see msdn:
http://msdn.microsoft.com/en-us/library/system.io.directory.move.aspx
Use Move like this:
System.IO.Directory.Move("old name", "new name");
I need some help in renaming some images in a directory located at /images/graphicsLib/.
All image names in /graphicsLib/ have naming convention that looks like this:
400-60947.jpg. We call the "400" part of the file the prefix and we call the "60957" part the suffix. The entire file name we call the sku.
So if you saw the contents of /graphicLib/ it would look like:
400-60957.jpg
400-60960.jpg
400-60967.jpg
400-60968.jpg
402-60988.jpg
402-60700.jpg
500-60725.jpg
500-60733.jpg
etc...
Using C# & System.IO , what is an acceptable way to rename all image files base on the prefix of the file name? Users need to be able to enter in the current prefix, see all images in the /graphicsLib/ that match, then enter in the new prefix to have all those files renamed with the new prefix. Only the prefix of the file gets renamed, the rest of the file name needs to be unchanged.
What I have so far is:
//enter in current prefix to see what images will be affected by
// the rename process,
// bind results to a bulleted list.
// Also there is a textbox called oldSkuTextBox and button
// called searchButton in .aspx
private void searchButton_Click(object sender, EventArgs e)
{
string skuPrefix = oldSkuTextBox.Text;
string pathToFiles = "e:\\sites\\oursite\\siteroot\\images\graphicsLib\\";
string searchPattern = skuPrefix + "*";
skuBulletedList.DataSource = Directory.GetFiles(pathToFiles, searchPattern);
skuBulletedList.DataBind();
}
//enter in new prefix for the file rename
//there is a textbox called newSkuTextBox and
//button called newSkuButton in .aspx
private void newSkuButton_Click(object sender, EventArgs e)
{
//Should I loop through the Items in my List,
// or loop through the files found in the /graphicsLib/ directory?
//assuming a loop through the list:
foreach(ListItem imageFile in skuBulletedList.Items)
{
string newPrefix = newSkuTextBox.Text;
//need to do a string split here?
//Then concatenate the new prefix with the split
//of the string that will remain changed?
}
}
You could look at string.Split.
Loop over all files in your directory.
string[] fileParts = oldFileName.Split('-');
This will give you an array of two strings:
fileParts[0] -> "400"
fileParts[1] -> "60957.jpg"
using the first name in your list.
Your new filename then becomes:
if (fileParts[0].Equals(oldPrefix))
{
newFileName = string.Format("(0)-(1)", newPrefix, fileParts[1]);
}
Then to rename the file:
File.Move(oldFileName, newFileName);
To loop over the files in the directory:
foreach (string oldFileName in Directory.GetFiles(pathToFiles, searchPattern))
{
// Rename logic
}
Actually you should iterate each of the files in the directory and rename one by one
To determine the new file name, you may use something like:
String newFileName = Regex.Replace("400-60957.jpg", #"^(\d)+\-(\d)+", x=> "NewPrefix" + "-" + x.Groups[2].Value);
To rename the file, you may use something like:
File.Move(oldFileName, newFileName);
If you are not familiar with regular expressions, you should check:
http://www.radsoftware.com.au/articles/regexlearnsyntax.aspx
And download this software to pratice:
http://www.radsoftware.com.au/regexdesigner/