I tried creating a program that tells you if a directory exists or not, but no matter what I input, it always comes up as not existing.
My Code:
using System;
using System.IO;
class TestFileAndDirectory
{
public static void Main()
{
string input;
input = Console.ReadLine();
if ( Directory.Exists(input))
{
Console.WriteLine("Exists");
}
else
{
Console.WriteLine("Doesn't Exist");
}
Console.ReadLine();
}
}
At first I just thought maybe it was my logic, so I tried this code from the book: Microsoft Visual C# 2010: Comprehensive Ch.14:
using System;
using System.IO;
public class DirectoryInformation
{
public static void Main()
{
string directoryName;
string[] listOfFiles;
Console.Write("Enter a folder >> ");
directoryName = Console.ReadLine();
if(Directory.Exists(directoryName))
{
Console.WriteLine("Directory exists, " +
"and it contains the following:");
listOfFiles = Directory.GetFiles(directoryName);
for(int x = 0; x < listOfFiles.Length; ++x)
Console.WriteLine(" {0}", listOfFiles[x]);
}
else
{
Console.WriteLine("Directory does not exist");
}
}
}
When I tried this code it did not work either not even if I put it into the same base folder as the directory I'm trying to find.
Path in question: C:\C#\Chapter.14\Cat Haikus
Path of Program: C:\C#\Chapter.14\TestFilesAndDirectories.cs
The path parameter is permitted to specify relative or absolute path
information. Relative path information is interpreted as relative to
the current working directory.
Source: https://msdn.microsoft.com/en-us/library/system.io.directory.exists(v=vs.110).aspx
If your input string is only a folder name like "Chapter. 14" (relative path), then this folder must exist in the path of your executable file. Like PathOfTheExecutableFile\Chapter. 14.
If the folder is in a completely different place, use absolute paths. Like C:\Users\theuser\Desktop\Chapter. 14.
Update:
Since you want to check C:\C#\Chapter.14\Cat Haikus folder, you could check if it exists using
if (Directory.Exists(#"C:\C#\Chapter.14\Cat Haikus")){
Console.WriteLine("Exists");
}
I don't know your exact folder tree structure, but if your executable file is in a subfolder of C:\C#\Chapter.14\, you could also use Directoy.GetParent() method.
Related
I am using this to get file location from user side but user give the full path but I got only File name not a full path.
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExampleForChecking
{
internal class Program
{
static void Main(string[])
{
Console.WriteLine("Enter file name:");
string v = Console.ReadLine();
var applicationPath = Path.GetDirectoryName(v);
Console.WriteLine(applicationPath);
}
}
}
which are change required for my code to get the full path.
To get the full path of the process running, you can use
var fullPath = Environment.CurrentDirectory;
GetDirectoryName ist tricky. It always removed the last section.
userInput = "C:\temp\CrossReferencedContent.txt"
Path.GetDirectoryName(userInput):
Result: "C:\temp"
userInput = "C:\temp"
Path.GetDirectoryName(userInput):
Result: "C:\"
userInput = "C:\temp\"
Path.GetDirectoryName(userInput):
Result: "C:\temp"
To get the correct output make sure the path ends with a \ or a filename.
Update based on your comment:
You can use File.Exists(v) to validate the Path.
Console.WriteLine("Enter the file path:");
string sourcePath = Console.ReadLine();
I've created a simple class that writes and reads json data with a txt file:
using System;
using System.IO;
using Newtonsoft.Json;
namespace JsonTest1
{
class Program
{
private const string filePath = #"..\jsonData.txt";
static void Main(string[] args)
{
JsonFileTest();
NewPerson();
DeSerializer();
Console.ReadLine();
}
//Tests if the project's storage file exists.
public static void JsonFileTest()
{
bool exists = File.Exists(filePath);
if (exists)
{
Console.WriteLine("File exists at filepath " + filePath);
}
else
{
Console.WriteLine(filePath + " not found.");
}
}
//Creates a test object of 'Person' then passes it to the serializer method.
public static void NewPerson()
{
Person person = new Person();
person.Name = "John Wick";
person.Age = 999;
SerializeMethod(person);
}
//Turns an object into JSON data and writes it to file.
static void SerializeMethod(Person person)
{
File.WriteAllText(filePath, JsonConvert.SerializeObject(person));
Console.WriteLine("Test name and age copied to file.");
}
//Turns JSON data from file into an object.
static void DeSerializer()
{
Person person2 = JsonConvert.DeserializeObject<Person>(File.ReadAllText(filePath));
if (person2 != null)
{
Console.WriteLine("Json-to-C# test data: " + person2.Name + ", " + person2.Age);
}
else
{
Console.WriteLine("No data received for json-to-C# test object.");
}
}
}
}
The issue is, if I set filePath to be something like #"C:\Users\User\Documents\json.txt", then it will create a text file that I can see the data in afterwards. If filePath is local, e.g. #"..\jsonData.txt", I open the file and it's empty, even though my program can read correctly from it at runtime. Why isn't the data saving when I use the local file route?
Things I've already tried: Using a .json file instead of a .txt file. Running Visual Studio as administrator.
You're looking in the wrong folder. Your program will be executed from the bin\debug folder or something. .. then is the bin folder.
A general approach for resolving "file not found" problems is to use SysInternals Process Monitor, a free program. Add a filter with the properties Path, contains, jsonData.txt, click Add and then let your program run.
This will reveal the full path:
Then click on Jump to... in the context menu to reveal that path.
You can check the full path for any path expression like this
var fp = System.IO.Path.GetFullPath(#"..\jsonData.txt");
I have a large directory of folders and files that contain a space at the end of the name, I'm trying to rename the directories with that space to one without, so that another application would be able to access it.
I'm using C# (but if there's a better option that would fix that issue please suggest) and here's my entire code:
using System;
using System.IO;
using System.Text.RegularExpressions;
namespace removing_spaces_in_directories_names
{
class Program
{
public static string path = "../../../old_directory";
static void Main(string[] args)
{
DirectoryInfo di = new DirectoryInfo(path);
WalkDirectoryTree(di);
Console.ReadLine();
}
static void WalkDirectoryTree(System.IO.DirectoryInfo root)
{
if (root.Name != "old_directory")
{ renameDirectory(root); }
DirectoryInfo[] diArr = root.GetDirectories();
foreach(DirectoryInfo di in diArr)
{
WalkDirectoryTree(di);
}
}
static void renameDirectory(System.IO.DirectoryInfo dir)
{
Console.WriteLine("renaming: " + dir.FullName);
string newName = ReplaceLastOccurrence(dir.FullName, " ", "");
if (Directory.Exists(dir.FullName) == false)
{
//dir.MoveTo(newName);
String oldName = #"\\?\"+dir.FullName;
Directory.Move(oldName,newName);
}
}
public static string ReplaceLastOccurrence(string Source, string Find, string Replace)
{
int place = Source.LastIndexOf(Find);
if (place == -1)
return Source;
string result = Source.Remove(place, Find.Length).Insert(place, Replace);
return result;
}
}
}
I have tried adding "\?\" to the beginning of the folder name as suggested here but that's not working, the error I'd get if I add it is: Illeagal characters in path.
On the other hand if I use dir.MoveTo(newName); without the "\?\" characters I'd get the error: Could not find a part of the path 'Volunteer Information '
How can I go through this if at all? would perhaps running this application on linux rather than windows help?
For each directory that you want to rename (remove the trailing space at the end in this case), let's say your DirectoryInfo variable is called di
You want to do this:
string oldName = di.FullName;
string newName = oldName.TrimEnd();
Directory.Move(oldName, newName);
I rewrote this in a PHP application that's sitting on linux and it worked.
In C# how to know that a file has been inserted into the Folder. I need this in C#.
Use FileSystemWatcher Class to accomplish This task.
Please refer
http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx
http://www.codeproject.com/Articles/2157/A-NET-File-System-Watcher
You can determine whether a specified file exists using the Exists method of the File class in the System.IO namespace:
bool System.IO.File.Exists(string path)
For ex:
using System;
using System.IO;
class Program
{
static void Main()
{
// See if this file exists in the SAME DIRECTORY.
if (File.Exists("TextFile1.txt"))
{
Console.WriteLine("The file exists.");
}
// See if this file exists in the C:\ directory. [Note the #]
if (File.Exists(#"C:\tidy.exe"))
{
Console.WriteLine("The file exists.");
}
// See if this file exists in the C:\ directory [Note the '\\' part]
bool exists = File.Exists("C:\\lost.txt");
Console.WriteLine(exists);
}
}
To get the Application's root I am Currently using:
Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6)
But that feels sloppy to me. Is there a better way to get the root directory of the application and set that to the working directory?
So, you can change directory by just using Envrionment.CurrentDirectory = (sum directory). There are many ways to get the original executing directoy, one way is essentially the way you described and another is through Directory.GetCurrentDirectory() if you have not changed the directory.
using System;
using System.IO;
class Test
{
public static void Main()
{
try
{
// Get the current directory.
string path = Directory.GetCurrentDirectory();
string target = #"c:\temp";
Console.WriteLine("The current directory is {0}", path);
if (!Directory.Exists(target))
{
Directory.CreateDirectory(target);
}
// Change the current directory.
Environment.CurrentDirectory = (target);
if (path.Equals(Directory.GetCurrentDirectory()))
{
Console.WriteLine("You are in the temp directory.");
}
else
{
Console.WriteLine("You are not in the temp directory.");
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
ref
What is it that you want; the working directory, or the directory in which the assembly is located?
For the current directory, you can use Environment.CurrentDirectory. For the directory in which the assembly is located, you can use this:
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)