Getting function to Know the Insertion of file in a folder - c#

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);
}
}

Related

Json data is saved differently depending on local or root filepath

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");

c# Unauthorized exception

Hey guys I got this error I have tried to run program as administrator, no luck still get this error I don't get why it can't clean the shortcuts in the recent documents folder, this is my code:
//this will delete the the files in the Recent Documents directory
private void DeleteRecentDocuments(string RecentDocumentsDirectory)
{
//this is the directory and parameter which we will pass when we call the method
DirectoryInfo cleanRecentDocuments = new DirectoryInfo(RecentDocumentsDirectory);
//try this code
try
{
//loop through the directory we use the getFiles method to collect all files which is stored in recentDocumentsFolder variable
foreach(FileInfo recentDocumentsFolder in cleanRecentDocuments.GetFiles())
{
//we delete all files in that directory
recentDocumentsFolder.Delete();
}
}
//catch any possible error and display a message
catch(Exception)
{
MessageBox.Show("Error could not clean Recent documents directory, please try again");
}
}
I call this method above but dw bout that too much its just calling the method and parameter is the directory. If you want I can post that to.
According to MSDN, FileInfo.Delete() will throw UnauthorizedAccessException when
Source
In order to delete all the files in a directory could do
foreach (string filePath in Directory.GetFiles(recentDocumentsFolder))
{
File.Delete(filePath);
}
If you want to delete the entire directory and any files and subfolders within it you could call
Directory.Delete(recentDocumentsFolder, true);
Your code work for me without any exception, I have select recent document folder using this way and work perfect
System.Environment.GetFolderPath(Environment.SpecialFolder.Recent)
here is my test solution using console application
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string rd = System.Environment.GetFolderPath(Environment.SpecialFolder.Recent);
DeleteRecentDocuments(rd);
Console.ReadLine();
}
//this will delete the the files in the Recent Documents directory
private static void DeleteRecentDocuments(string RecentDocumentsDirectory)
{
//this is the directory and parameter which we will pass when we call the method
DirectoryInfo cleanRecentDocuments = new DirectoryInfo(RecentDocumentsDirectory);
//try this code
try
{
//loop through the directory we use the getFiles method to collect all files which is stored in recentDocumentsFolder variable
foreach (FileInfo recentDocumentsFolder in cleanRecentDocuments.GetFiles())
{
//we delete all files in that directory
recentDocumentsFolder.Delete();
}
}
//catch any possible error and display a message
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Update
some files inside that directory is protected not only for delete but also copy so you can't delete them but most of others can be delete using below code, I have tested
private static void DeleteRecentDocuments(string RecentDocumentsDirectory)
{
//this is the directory and parameter which we will pass when we call the method
DirectoryInfo cleanRecentDocuments = new DirectoryInfo(RecentDocumentsDirectory);
//try this code
try
{
//loop through the directory we use the getFiles method to collect all files which is stored in recentDocumentsFolder variable
foreach (FileInfo recentDocumentsFolder in cleanRecentDocuments.GetFiles())
{
//we delete all files in that directory
File.Delete(RecentDocumentsDirectory + recentDocumentsFolder);
}
}
//catch any possible error and display a message
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Hope this will help you

Directory Check Won't Work

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.

How to get the current directory path of application's shortcut

I want to get the current directory path but not of the application location but of it's shortcut location.
I tried these but they return the application's location.
Directory.GetCurrentDirectory();
Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
According to the process API reference in MSDN, the process STARTUPINFO struct for a given process contains the information about the shortcut .lnk file in the title member. There is a flag present in the dwFlags struct member that is set when this is the case - so it appears that this is not always set (im guessing if you ran the exe directly)
From MSDN:
STARTF_TITLEISLINKNAME: 0x00000800
The lpTitle member contains the path of the shortcut file (.lnk) that the user invoked
to start this process. This is typically set by the shell when a .lnk file pointing to
the launched application is invoked. Most applications will not need to set this value.
This flag cannot be used with STARTF_TITLEISAPPID.
Reference here.
If adding a COM Object reference is not a problem , Add COM Object Reference - Windows Script Host Object Model
i ran this code in my desktop folder and it did work. for current folder use - Environment.CurrentDirectory
using System;
using System.IO;
using IWshRuntimeLibrary; //COM object -Windows Script Host Object Model
namespace csCon
{
class Program
{
static void Main(string[] args)
{
// Folder is set to Desktop
string dir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
var di = new DirectoryInfo(dir);
FileInfo[] fis = di.GetFiles();
if (fis.Length > 0)
{
foreach (FileInfo fi in fis)
{
if (fi.FullName.EndsWith("lnk"))
{
IWshShell shell = new WshShell();
var lnk = shell.CreateShortcut(fi.FullName) as IWshShortcut;
if (lnk != null)
{
Console.WriteLine("Link name: {0}", lnk.FullName);
Console.WriteLine("link target: {0}", lnk.TargetPath);
Console.WriteLine("link working: {0}", lnk.WorkingDirectory);
Console.WriteLine("description: {0}", lnk.Description);
}
}
}
}
}
}
}
Code Reference from Forum : http://www.neowin.net/forum/topic/658928-c%23-resolve-lnk-files/
Try this:
Environment.CurrentDirectory
From MSDN:
Gets or sets the fully qualified path of the current working directory.
I think you will need to use COM and add a reference to "Microsoft Shell Control And Automation", as described in this blog post:
Here's an example using the code provided there:
namespace Shortcut
{
using System;
using System.Diagnostics;
using System.IO;
using Shell32;
class Program
{
public static string GetShortcutTargetFile(string shortcutFilename)
{
string pathOnly = System.IO.Path.GetDirectoryName(shortcutFilename);
string filenameOnly = System.IO.Path.GetFileName(shortcutFilename);
Shell shell = new Shell();
Folder folder = shell.NameSpace(pathOnly);
FolderItem folderItem = folder.ParseName(filenameOnly);
if (folderItem != null)
{
Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
return link.Path;
}
return string.Empty;
}
static void Main(string[] args)
{
const string path = #"C:\link to foobar.lnk";
Console.WriteLine(GetShortcutTargetFile(path));
}
}
}
using System.Reflection;
string currentAssemblyDirectoryName = Path.GetDirectoryName(
Assembly.GetExecutingAssembly()
.Location
);
Also for webapplications you can use:
Web Applications:
Request.PhysicalApplicationPath
http://msdn.microsoft.com/en-us/library/system.web.httprequest.physicalapplicationpath.aspx
to grap the applicationpath :)
Since creating the shortcut is part of the workflow, just set the working directory to "%cd%" for the shortcut then, in the app, use:
Environment.CurrentDirectory
Obviously, you would want to capture this value before any code your app calls can change it.
When creating a shortcut using Windows Explorer, you don't have the option of setting the working directory. So, after creating it, open its property page by right-clicking on it and selecting Properties, then set the Start in field to %cd%. After creating such a shortcut, you can move or copy it to the folders in which you want the app to run.
If you do not want to use a COM object as suggested in the other answers
You can open the file as a regular text file, split on the \x00 0 char, and inspect the resulting string array. One of them will be obviously the link target: something like "C:\path\to\file" or in case of UNC "\\computers\path\to\file".
string lnkFilePath "...";
var file = System.IO.File.ReadAllText(lnkFilePath);
var contents = Regex.Split(file, "[\x00]+");
var paths = contents.Where(line => Regex.IsMatch(line, #"^([A-Z]:\\|^\\\\)\S+.*?"));
Use GetStartupInfoW, it will tell you the .lnk file that was launched to start the program.

How do I get/set a winforms application's working directory?

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)

Categories

Resources