Creating a directory in AppData after launching my application [closed] - c#

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 3 years ago.
Improve this question
I am working on an application developed in C # .net WPF, I wanted to know how to make every launch of my application,
Detect if there is an "Affaires" directory in "%AppData%\Roaming\N.O.E" and, if not, create the directory.
Detect if there is an "Affaires" directory in "C:\N.O.E" and, if there is, prompt the user if they want to move the directory to AppData. If yes, move the directory.
The installation is done with an administrator account.
Should the detection code for my application be in the class "App.XAML.cs"?
Code of the method that launches the application is:
protected override void OnStartup(StartupEventArgs e)
{
Application.Current.DispatcherUnhandledException +=
new
try
{
// Créé le répertoire des traces s'il n'existe pas déjà
string cwd = Directory.GetCurrentDirectory();
string logPath = Path.Combine(cwd, "log");
if (!Directory.Exists(logPath))
{
Directory.CreateDirectory(logPath);
}
// Log4Net configuration
FileInfo log4NetConfig = new FileInfo(Path.Combine(cwd,
"Log4net.config"));
log4net.Config.XmlConfigurator.Configure(log4NetConfig);
// Récupère la version de l'application
System.Reflection.Assembly assembly =
System.Reflection.Assembly.GetExecutingAssembly();
Version version = assembly.GetName().Version;
UpdateService.CheckingForUpdates();
Log.Info("Démarrage de l'application " +
OtherHelper.GetAppSetting("NomApplication", "N.O.E") + "
version " + version);
ConfigService.InitializeConfigPathAndModificationDate();
TagService.InitializeReferential();
}
catch (Exception ex)
{
////////
}
base.OnStartup(e);
}

Depending which AppData folder you need, you can retrieve the folder you need using Environment.GetFolderPath().
So, to check for directory "Affaires" in AppData\Roaming\N.O.E create it if it doesn't exist, for example:
string appDataLocalPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string affairesDirPath = appDataRoamingPath + "\\N.O.E.\\Affaires";
if(!Directory.Exists(affairesDirPath))
{
DirectoryInfo affairesDir = Directory.CreateDirectory(affairesDirPath);
//Do anything else you need to with the directory here.
}
If you only need to create the directory without doing anything else with it, then you can simple use Directory.CreateDirectory(affairesDirPath);; it will not create the directory if it already exists.
For your other directory, you can do the following:
string affairesDirPath = "C:\\N.O.E.\\Affaires";
if(Directory.Exists(affairesDirPath))
{
//Move the directory
}

Related

File.Exists always returns false [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
My app is a 32 bit .Net VS 2017 app. File.Exists always returns false in my app. Either running in VS, deployed locally, or as admin. Running on a Windows 10 64 bit system. Paths are good because the File.Copy works (but always since File.Exist isn't working. I don't want File.Copy to run unless file doesn't exist. Maybe suggestions for a workaround if I can't get it to work? File permissions shouldn't be a problem since the file is in the Documents folder. Maybe a better SpecialFolder to use than MyDocuments? Any help would be appreciated. Thanks in advance. Code below.
// Class variables
public static string appPath = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
"\\Lottery Analyzer Expert International";
public static string dbPath = appPath + "\\database\\";
public static string dbFile = "Histories.sqlite";
// Class method
public void copyInputFiles_db()
{
string dest = dbPath + dbFile;
string src = Application.StartupPath + "\\database\\" + dbFile;
if (!File.Exists(dest)) { }
{
File.Copy(src, dest, true); // if input files not found in appPath copy from install folder
bool do_download = true;
DialogResult dialogResult2 = MessageBox.Show(
"The history database was copied from the application's startup to it's working dirctory. This happens when first running " +
"the application or the history file is missing. Would you like to update that file from the web?",
"Download file?", MessageBoxButtons.YesNo);
if (dialogResult2 == DialogResult.Yes)
{
do_download = true;
}
else if (dialogResult2 == DialogResult.No)
{
do_download = false;
}
if (do_download)
downloadAllTheHistoryFIles_db();
}
printTextFiles();
}
You know that the code below the if is always executed?
if (!File.Exists(dest)) { } // << the { } is the IF scope
{ // <- this is a new scope also, but not part of the if..
File.Copy(src, dest, true);
bool do_download = true;
// *SNIP*
}
Remove the { } behind the if

Make file not moveable, copyable or deleteable? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I here from CodeProject, but they don't seem to have an answer to my question. I just want a desktop file to have security permission(make the file not moveable, copyable or deletable). This is possible to do manually in the file's "properties!. I am using C#, your help is much appreciated - thanks!
As a helper said below, if it is not possible to make a readable file uncopyable...is it possible to make it not moveable and deletable?
All these things are possible EXCEPT being uncopyable. Readable files can always be copied unless you restrict ALL copying on the system (which is a formidable task). However you can certainly prevent it from being moved or deleted.
From a file permissions perspective, you need to set the owner to an administator, then grant read-only permissions to the user in question. This will allow them to read the file but not delete or move it.
Doing so is quite simple using the FileInfo.SetAccessControl method in System.IO; here's the documentation to help out.
Edit to add example, credit to MS for the example:
using System;
using System.IO;
using System.Security.AccessControl;
namespace FileSystemExample
{
class FileExample
{
public static void Main()
{
try
{
string FileName = "c:/test.txt";
Console.WriteLine("Adding access control entry for " + FileName);
// Add the access control entry to the file.
// Before compiling this snippet, change MyDomain to your
// domain name and MyAccessAccount to the name
// you use to access your domain.
AddFileSecurity(FileName, #"MyDomain\MyAccessAccount", FileSystemRights.ReadData, AccessControlType.Allow);
Console.WriteLine("Removing access control entry from " + FileName);
// Remove the access control entry from the file.
// Before compiling this snippet, change MyDomain to your
// domain name and MyAccessAccount to the name
// you use to access your domain.
RemoveFileSecurity(FileName, #"MyDomain\MyAccessAccount", FileSystemRights.ReadData, AccessControlType.Allow);
Console.WriteLine("Done.");
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
// Adds an ACL entry on the specified file for the specified account.
public static void AddFileSecurity(string FileName, string Account, FileSystemRights Rights, AccessControlType ControlType)
{
// Create a new FileInfo object.
FileInfo fInfo = new FileInfo(FileName);
// Get a FileSecurity object that represents the
// current security settings.
FileSecurity fSecurity = fInfo.GetAccessControl();
// Add the FileSystemAccessRule to the security settings.
fSecurity.AddAccessRule(new FileSystemAccessRule(Account,
Rights,
ControlType));
// Set the new access settings.
fInfo.SetAccessControl(fSecurity);
}
// Removes an ACL entry on the specified file for the specified account.
public static void RemoveFileSecurity(string FileName, string Account, FileSystemRights Rights, AccessControlType ControlType)
{
// Create a new FileInfo object.
FileInfo fInfo = new FileInfo(FileName);
// Get a FileSecurity object that represents the
// current security settings.
FileSecurity fSecurity = fInfo.GetAccessControl();
// Add the FileSystemAccessRule to the security settings.
fSecurity.RemoveAccessRule(new FileSystemAccessRule(Account,
Rights,
ControlType));
// Set the new access settings.
fInfo.SetAccessControl(fSecurity);
}
}
}

C# Error Access to the path 'C:\Windows\system32\Com\dmp' is denied When Windows Startup

thanks because you has been come to this post.
I have an error with my script, that log says:
Access to the path 'C:\Windows\system32\Com\dmp' is denied.
I want to set my application to windows startup, so when that computer client started, my software is automatically running. So i put this script on my Main Load.
private void Main_Load(object sender, EventArgs e)
{
//Menjadikan software ke dalam Startup Windows, sehingga dapat berjalan ketika pc pertama kali dinyalakan
RegistryKey reg = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
reg.SetValue("PR Reminder", Application.ExecutablePath.ToString());
listMapel();
bool notif = Properties.Settings.Default.Notification;
if (notif == true)
{
checkExpired(); //Mengecek tanggal penyerahan dan pemberian
}
The result is work. But I'm getting an error like this.
After explored more deeply, the center of the issue is the method listMapel();
where he was tasked to search for files ending in .db in the local directory.
I dont know why this method is got error. When i try to remove this method, my application running fine when startup.
I think the problem is on system.io.
This is my listMapel(); method script
public void listMapel()
{
comboListMapel.Items.Clear();
string path = Directory.GetCurrentDirectory(); //Lokal direktori
string[] files = Directory.GetFiles(path, "*.db", SearchOption.AllDirectories);
foreach (string file in files)
{
nama = file.Split(".".ToCharArray()); //Hasil result yang ditampilkan Matapelajaran.db (Tapi dengan ini kita mengambil string sebelum .db
comboListMapel.Items.Add(Path.GetFileName(nama[0]));
}
}
You should always run as an administrator.
Hope this helps link
And another one
Give the access to your file like FileMode.Create, FileAccess.Write, FileShare.None
try this it will may work.

Edit Skype's config.xml

I'm trying to edit Skype's config.xml file from code. It works fine, but after change Skype delete it and generate another one, undoing all my changes. For example, code:
public Core()
{
try
{
var processes = Process.GetProcessesByName("Skype");
if (processes.Length == 0)
{
AddRegistryKeys();
RemovePlaceholder();
}
else
{
RestartSkypeAndRun(processes[0],
() =>
{
AddRegistryKeys();
RemovePlaceholder();
});
}
Environment.Exit(0);
}
catch (Exception ex)
{
MessageBox.Show(string.Format("{0} - {1}", ex.GetType(), ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
Environment.Exit(-1);
}
}
private static void RemovePlaceholder()
{
string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string skypePath = Path.Combine(appDataPath, "Skype");
foreach (var configPath in Directory.EnumerateFiles(skypePath, "config.xml", SearchOption.AllDirectories))
{
string userConfig = File.ReadAllText(configPath);
string fixedConfig = userConfig.Remove("<AdvertPlaceholder>1</AdvertPlaceholder>");
File.Move(configPath, configPath + ".bak");
File.WriteAllText(configPath, fixedConfig);
}
}
private static void RestartSkypeAndRun(Process skypeProc, Action action)
{
string skypeExePath = skypeProc.Modules[0].FileName;
skypeProc.Kill();
skypeProc.WaitForExit();
Thread.Sleep(TimeSpan.FromMilliseconds(500)); //just in case
action();
Process.Start(skypeExePath);
}
So how can it be done? I have no idea, except blocking file modification, e.g. change ACL and other permissions for file, set readonly attribute e.t.c.
See https://www.safaribooksonline.com/library/view/skype-hacks/0596101899/ch04s04.html
"Always stop Skype from running (by right-clicking on Skype in the system tray and choosing Quit) before making any changes to config.xml (or shared.xml), because even though your editor may tell you it has saved your updated version of config.xml, you may find that Skype ignores your changes and they are missing when you reopen config.xml. The procedure for editing any of Skype's configuration files should go like this: quit Skype (that is, stop it from running), edit (or delete) the configuration file, save the changes, and restart Skype."
C:\Documents and Settings\Username\Application Data\Skype\Skypename\config.xml
"There is another file, shared.xml, from which Skype obtains configuration information that is common to all users of Skype on the same Windows machine... You also can edit this file to tweak how Skype behaves, but the scope for tweaking is far more limited than for config.xml. You typically can find shared.xml in these locations on each platform:
Windows (version 1.3 and before)
C:\Documents and Settings\All Users\Application Data\Skype\shared.xml
Windows (version 1.4 and after)
C:\Documents and Settings\Username\Application Data\Skype\shared.xml
"

%AllUsersProfile%(%PROGRAMDATA%) gives a repetitive file path

I have an application written in C#, and I am seeking to write some information to the hidden ProgramData in order to access the same connection string from both the application's front end and back end.
I am accessing the directory using path variables as follows:
private bool ProgramDataWriteFile(string contentToWrite)
{
try
{
string strProgramDataPath = "%PROGRAMDATA%";
string directoryPath = Environment.ExpandEnvironmentVariables(strProgramDataPath) + "\\MyApp\\";
string path = Environment.ExpandEnvironmentVariables(strProgramDataPath)+"\\MyApp\\ConnectionInfo.txt";
if (Directory.Exists(directoryPath))
{
System.IO.StreamWriter file = new System.IO.StreamWriter(path);
file.Write(contentToWrite);
file.Close();
}
else
{
Directory.CreateDirectory(directoryPath);
System.IO.StreamWriter file = new System.IO.StreamWriter(path);
file.Write(contentToWrite);
file.Close();
}
return true;
}
catch (Exception e)
{
}
return false;
}
This seems to work correctly. However, my question is, when I used this path variable: %AllUsersProfile%(%PROGRAMDATA%)
instead, it expanded into an illegal(and redundant) file path : C:\ProgramData(C:\ProgramData)\
However, I thought that the latter path variable was the correct full name. Was I just using it incorrectly? I need to ensure that this connection info will be accessible to all users, will just using %PROGRAMDATA% allow that? I am using Windows 7 in case that is relevant.
From here:
FOLDERID_ProgramData / System.Environment.SpecialFolder.CommonApplicationData
The user would never want to browse here in Explorer, and settings changed here should affect every user on the machine. The default location is %systemdrive%\ProgramData, which is a hidden folder, on an installation of Windows Vista. You'll want to create your directory and set the ACLs you need at install time.
So, just use %PROGRAMDATA%, or better still:
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)

Categories

Resources