create folder and copy set of files to local disk - c#

i am trying to create a folder and copy some images into it using c# wpf application.
curName = txt_PoemName.Text;
// Specify a "currently active folder"
string activeDir = #"C:\Program Files\Default Company Name\Setup2\Poems";
//Create a new subfolder under the current active folder
string newPath = System.IO.Path.Combine(activeDir, curName);
// Create the subfolder
System.IO.Directory.CreateDirectory(newPath);
foreach(DictionaryEntry entry in curPoem){
string newFilePath = System.IO.Path.Combine(newPath, entry.Key.ToString() + Path.GetExtension(entry.Value.ToString()));
System.IO.File.Copy(entry.Value.ToString(), newFilePath, true);
}
i have successfully created the folder and images. and also i can access them via application. but i cant see them in the location on my local disk. when i restart the machine , then application also cant see them.how can i solve this?

Sounds like you have encountered UAC Data Redirection
http://blogs.windows.com/windows/b/developers/archive/2009/08/04/user-account-control-data-redirection.aspx
You need to either force the application to run as an administrator.
How do I force my .NET application to run as administrator?
Or not save your data in a sensitive area. I would recommend saving in a subfolder of
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);

Related

Why can't I create a file in LocalApplicationData? C# , VS 2022, Windows 11

I know that there are restrictions to file operations, but SpecialFolder.LocalApplicationData is supposed to be for application use.
string _myFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "MyFile.txt"); //Line1
Console.WriteLine(_myFilePath); //Line2
Console.WriteLine(File.Exists(_myFilePath)); //Line3
Console.WriteLine(File.Create(_myFilePath)); //Line4
This is the console output:
The program stops at the 4th line and VS 2022 shows this error:
How can I create or delete files/folders in SpecialFolder.LocalApplicationData ? Or which folder is recommended for this kind of file/folder operations?
Using Windows 11, VS 2022 17.2.0 Preview 5.0 and NET 6.0 without administrator privileges:
Your code worked fine for me.
Output:
C:\Users\Edgar\AppData\Local\MyFile.txt
False
System.IO.FileStream
But here is my suggestion:
Check the ACLs of your directory: Is your account permitted for creating new files?
(Right-click the directory -> Properties -> Security -> Select your own user and check your permissions.)
Usually you should not create files directly under your %localappdata% directory.
If you need a temp-file, I would recommend to use Path.GetTempFileName() for getting a unique file name.
If you want to store files for a longer time, then I would recommend to create a directory for your application in %localappdata% and save the files there.
Sample:
string myApplicationDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "MyApplication");
string myApplicationFile = Path.Combine(myApplicationDirectory, "myFile.txt");
if (!Directory.Exists(myApplicationDirectory)) {
Console.WriteLine($"Creating directory: {myApplicationDirectory}");
Directory.CreateDirectory(myApplicationDirectory);
}
File.Create(myApplicationFile);
Console.WriteLine($"File created: {myApplicationFile}");
Output:
Creating directory: C:\Users\Edgar\AppData\Local\MyApplication
File created: C:\Users\Edgar\AppData\Local\MyApplication\myFile.txt

UWP can write to files of many types in Downloads folder but cannot do the same for SQLite db file

Environment: Microsoft.Data.Sqlite.Core, SQLitePCLRaw.bundle_winsqlite3 2.0.1, Windows-10, VS2019- ver16.3.6
Following code works in my UWP app to create a a file in Downloads folder in Windows 10, and also can write to that file. But, as shown in the second code block below, when I do the same by creating an SQLite file, say, sqliteSample.db in the Downloads folder and then try to open that db it gives me the error shown below:
Following code snippet works for creating and writing to a file in Downloads folder:
StorageFile file = await Windows.Storage.DownloadsFolder.CreateFileAsync("sample.txt");
Windows.Storage.Pickers.FolderPicker folderPicker = new Windows.Storage.Pickers.FolderPicker
{
SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Downloads
};
folderPicker.FileTypeFilter.Add(".txt");
StorageFolder oPickedFolder = await folderPicker.PickSingleFolderAsync();
if (oPickedFolder != null)
{
//Application now has read/write access to all contents in the picked folder (including other sub-folder contents)
Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", oPickedFolder);
string sSQLDbPath = Path.Combine(oPickedFolder.Path, "sample.txt");
Windows.Storage.StorageFile sampleFile = await oPickedFolder.GetFileAsync("sample.txt");
await Windows.Storage.FileIO.WriteTextAsync(sampleFile, "Swift as a shadow");
}
Following code snippet successfully creates sqliteSample.db file in Downloads folder, but gives error shown below when trying to open it:
Remarks: Below error occurs at line db.Open(); of the following code. I've verified in the debug mode in VS2019 that the variable sSQLDbPath has the correct path and when I manually copy/paste that path to the Windows explorer, I can see the sqliteSample.db file in the same subfolder of the Downloads folder that also has the sample.txt file created from the above code and that works without error.
SQLite Error 14: 'unable to open database file'.
StorageFile file = await Windows.Storage.DownloadsFolder.CreateFileAsync("sqliteSample.db");
Windows.Storage.Pickers.FolderPicker folderPicker = new Windows.Storage.Pickers.FolderPicker
{
SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Downloads
};
folderPicker.FileTypeFilter.Add(".db");
StorageFolder oPickedFolder = await folderPicker.PickSingleFolderAsync();
if (oPickedFolder != null)
{
//Application now has read/write access to all contents in the picked folder (including other sub-folder contents)
Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", oPickedFolder);
string sSQLDbPath = Path.Combine(oPickedFolder.Path, "sqliteSample.db");
using (SqliteConnection db = new SqliteConnection($"Filename={sSQLDbPath}"))
{
db.Open();
String tableCommand = "CREATE TABLE IF NOT " +
"EXISTS MyTable (Primary_Key INTEGER PRIMARY KEY, " +
"Text_Entry NVARCHAR(2048) NULL)";
SqliteCommand createTable = new SqliteCommand(tableCommand, db);
createTable.ExecuteReader();
}
}
From File and folder permissions in the Downloads folder:
The user can give another app access to your
file by selecting the file from the file picker. Your app can also use
the file picker to get access to the files in the Downloads folder
that it didn't create.
Capabilities are not needed to create or access files in the Downloads
folder.
NOTE: This post did not help either.
Short story: SQLite can't see the downloads folder. It can only write to databases in the app's ApplicationData folders.
Longer explanation: Your app has full access only to a few locations (i.e. read only to its install folder and read-write to its application data). Other locations (libraries granted via capabilities, picked files or folders, downloads directory) are granted access by the file broker. The app uses this access via functions that adhere to the UWP app security model such as the Windows.Storage classes (as demonstrated in your working code to create the database) and CreateFileFromApp.
SQLite's default implementation doesn't use any of these methods that use the brokered file access, so ApplicationData is the only read-write location that the default SQLite implementation can use without modification. You can grant the app access elsewhere (e.g. with the broadFileSystemAccess capability), but SQLite doesn't by default use the right API to make use of that access.
In theory you could modify SQLite to use these API (probably in a SQLite virtual file system), but I'm not aware of any actual implementations which have done so.

Run local .html file in same directory as executable in web browser control (visual studio)

I can't seem to run a local .html file on web browser control that's in the same path as the application directory.
I am getting the current application directory, and adding my file name (such as "index.html") at the end of it however it doesn't build successfully.
What's wrong with my code?
string applicationDirectory = AppDomain.CurrentDomain.BaseDirectory
string myFile = Path.Combine(applicationDirectory, "/Media/index.html");
webBrowser1.Url = new Uri("file:///" + myFile);
You don't have to browse with an url , but with a local file path :
WebBrowser1.Navigate("../Media/index.html");

how to copy file to another server with different user account?

In my project, when user upload a file in the web page which hosted in serverA, the web page should also copy that to serverB. ServerA and serverB is under the same network which admin can access ServerB file from serverA via network drive(//servername/C$/folderpath).
string fileName = "my test.txt";
string sourcePath = #"C:\myFolder";
string targetPath = #"\\vmtest001\C$\myFolder\subFolder";
// Use Path class to manipulate file and directory paths.
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!System.IO.Directory.Exists(targetPath)) //error
{
System.IO.Directory.CreateDirectory(targetPath);
}
I have tried to copy that file to ServerB and the error message is
Access to the path '\vmtest001\C$\myFolder\subFolder'is denied.
I see some solutions for that are using a webserivce to move file, could anyone tell me the possibility of that?
Main question: How to copy file between different server?
Add this to your web.config:
<identity impersonate="true" userName="accountname" password="password" />
But this is not recommended.
You can start a service on ServerA, using FileSystemWatcher to monitor the upload files, copy file to serverB in this service。

Get DefaultAppPool AppData folder from the web application

I have a web application which is running from DefaultAppPool account. I want to write some files into the DefaultAppPool's AppData folder (or any other folder, which is 100% accessible from the account my application is running)
I've tried
Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData)
but for some reason, it returns an empty string.
Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile)
returns C:\\Users\DefaultAppPool as expected.
How can I get the AppData path for DefaultAppPool?
EDIT:
This code is executed in the Model
I do it like this:
var path = string.Format("{0}\\{1}", Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile), "AppData")
I did it like this:
string apPath = Path.Combine(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath, "App_Data");

Categories

Resources