For my work I have a varying list of appsettings.json files for different iterations of the same project. I have created a WinFormApp that has a series of buttons that basically copy the selected json file contents to my clipboard for me to then paste into the appsettings file for my project.
Every value in these settings files stays the same apart from one which we update on a monthly basis, I wrote some code that takes a text value entered on the form and updates this value into the Json files and then saves them.
private void UpdateNativeAppPaths(string newPath, string device)
{
var currentDirectory = Directory.GetCurrentDirectory();
var appSettingsFilesRoot =
Path.GetFullPath(Path.Combine(currentDirectory, "..", "..", "..", "AppSettingsFiles"));
var appSettingsPathsList = Directory.GetFiles(appSettingsFilesRoot, "*.*", SearchOption.AllDirectories);
foreach (var path in appSettingsPathsList.Where(path => path.EndsWith($"{device}.json")))
{
var myJsonResponse = File.ReadAllText(path);
var jObject = JsonConvert.DeserializeObject(myJsonResponse) as JObject;
var jToken = jObject?.SelectToken("AppSettings.NativeAppPath");
jToken?.Replace(newPath);
var updatedJson = jObject?.ToString();
File.WriteAllText(path, updatedJson);
}
}
This works when I run the application from the source files but I would like to publish and share this application with my colleagues however I assume that the published application does not have direct access to the directories that I am referencing or something like that.
Pretty much I want to know if there is a way for me to be able to get this logic working with a published version of my application. I tried including the "AppSettingsFiles" folder into the published directory but the app still appeared to be referencing the files from its own metadata maybe... I'm not sure, hopefully someone can help me, please let me know if you need more information?
Related
Hello StackOverflow community,
I'm working for a C# web application that can show all necessary files in one folder. For example, you have a folder named "Maps" that stores all information about New York City. I will describe this folder here: The bolded word is folders.
Folder Maps:
->NewYorkCity
->>satellite.png
->>coordinates.txt
->>bridges.png
->>Road1
->>>satellite1.png
->>>roads.txt
->>>houses.png
As you can see, inside folder Maps we have folder NewYorkCity, and inside of this, we have folder Road1. Now I want to collect all files that have "*.png" type. It means I want to collect all images inside the root folder. The problem here is the algorithm to collect the file. I have thought to use "for loops" but I don't know the number of subfolders so I assumed it was impossible.
Here is the code to list the file with specified type that I have used but it works for files that in one folder and doesn't have any subfolders.
DirectoryInfo dInfo = new DirectoryInfo(zipPath); //Assuming Test is your Folder
FileInfo[] Files = dInfo.GetFiles("*.png"); //Getting Text files
string str = "";
foreach (FileInfo file in Files)
{
str = str + ", " + file.Name;
}
I hope you understand my question. Thank you.
You could start by reading the documentation, where you would find System.IO.DirectoryInfo.
Create a DirectoryInfo instance, and use, depending on what you want/need, any of its methods
EnumerateDirectories()
EnumerateFiles()
EnumerateFileSystemInfos()
Like so:
DirectoryInfo di = new DirectoryInfo(#"c:\Maps");
foreach (var fsi in di.EnumerateFileSystemInfos("*", SearchOptions.AllDirectories)
{
// Do something useful with fsi here
}
This is really annoying problem and it's going to drive me mad. I like to read information such like files, directories ect. but my app cannot find anything OUTSIDE its folder it runs in.
I'm using Visual Studio 2015 and developing Windows Universal apps.
This routine under works very well if I change the directory inside the folder my app run like "Assets" and any other folder. But outside of my app folder result is zero, not even any errors :-(
Ok, Here is the simple code, What I Do Wrong?
private void GetThem_Click(object sender, RoutedEventArgs e)
{
string myDir = #"c:\mydir\";
string[] files;
files = Directory.GetFiles(myDir,"*.jpg");
foreach (string stuff in files)
{
RESULT.Text = RESULT.Text + stuff + " , ";
}
}
A quick search would have given you the answer : It is not possible to access the file system like a classic desktop app. The answer of #Rico Suter explain you what you can acces and how :
Directories which are declared in the manifest file (e.g. Documents, Pictures, Videos folder)
Directories and files which the user manually selected with the FileOpenPicker or FolderPicker
Files from the FutureAccessList or MostRecentlyUsedList
Files which are opened with a file extension association or via sharing
Once a file is picked by the user, you can add it to MostRecentlyUsedList or FutureAccessList to use it again later using this snippet (C#) from MSDN :
StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
// Add to MRU with metadata (For example, a string that represents the date)
string mruToken = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.Add(file, "20120716");
// Add to FA without metadata
string faToken = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(file);
}
Then store the retrieved token because you will need it to access the file using GetFileAsync(token)
I'm trying to use the Duplicati API to restore a single file.
About the Scenario: The whole thing runs on linux so it is compiled with mono. My backup contains two source Folders, so if I run Interface.ListSourceFolders() I get an Array of two.
Desired result: I want to restore one single file (or Folder) from my backup
Current result: If I run the code below it restores all the backed up files (so Folder 1 and Folder 2) into the path in //Comment1.
List<string> files = new List<string>();
files.Add("path"); //Comment1
Dictionary<string,string> options = new Dictionary<string,string>();
options["passphrase"] = MySettings.Password;
options["restore-time"] = date;
//Comment2
Interface i = new Interface("file:///path/to/archives", options);
string result = i.Restore(files.ToArray());
What I tried: I tried to set the path at //Comment1 to the absolute path (/desired/file/to/restore) or using the index of the source Folder (0/file/to/restore) and I also played around at //Comment2. e.g. I added something like options["restore-path"] = "/path/to/restore". I always get the same result.
Does anyone see what I'm doing wrong? Because I don't know what else I could try. There is almost no documentation so I don't know where to search. If someone knows a link for a good documentation I would be happy too!
In case if someone is interested. After trying around for hours I finally found out how to restore just a single file or folder. Here is what I'm doing now:
List<string> files = new List<string>();
files.Add("/restore/path"); //Comment1
Dictionary<string,string> options = new Dictionary<string,string>();
options["passphrase"] = MySettings.Password;
options["restore-time"] = date;
options["file-to-restore"] = "files"; //Comment2
Interface i = new Interface("file:///path/to/archives", options);
string result = i.Restore(files.ToArray());
At //Comment1 you need to set the desired restore path. In this folder all backup-set-folders are created (The folders from Interface.ListSourceFolders())
At //Comment2 you can specify the files to be restored in this form: 0/file/to/restore where 0 is the index of the source folder (Interface.ListSourceFolders()). If you need to restore multiple files you can do it by combining them into one string: e.g. Windows: 0/file1;1/file2 or Linux 0/file1:1/file2 (The difference is semicolon or colon)
Now there is just one more thing: You can not restore a folder with its files. You need to combine all files and sub-files in the string mentioned above.
I hope I could help somebody.
I have this piece of code:
string jsonPath = #"Model\Datamodel\UserData.json";
User userItem = JsonConvert.DeserializeObject<User>(user);
User.Add(userItem);
string content = user;
var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
var file = await folder.GetFileAsync(jsonPath);
await FileIO.WriteTextAsync(file,content);
Debug.WriteLine(String.Format("DONE"));
The "Done" debug line is written in console but it does not write anything to the file.
I also don't get any errors. When I debug and look at Folder and file I see that they are correctly.
Can anybody help?
You can't write to files in Windows.ApplicationModel.Package.Current.InstalledLocation, you need to use one of the other writeable locations available to you instead. (e.g. ApplicationData.Current.LocalFolder)
If you need to access the content of the file that was shipped with the package, I would suggest copying it to the local folder, and using the copy for read/write access.
I'm developing a C# asp.net web application. I'm basically done with it, but I have this little problem. I want to save xml files to the "Users" folder within my project, but if I don't psychically hard code the path "C:......\Users" in my project it wants to save the file in this "C:\Program Files (x86)\Common Files\microsoft shared\DevServer\10.0\Users" folder, this is an annoying problem because I can't use the hard coded directory on our web hosts server. Also, I have a checkbox list that populates from the the "DownloadLibrary" folder in my project, and its suppose to download the files from that fold but its also looking to the "C:\Program Files (x86)\Common Files\microsoft shared\DevServer\10.0\" folder for download even though its populating from the correct folder. I'm very confused by this, its the first time something like this has ever happened to me. Can anyone please help me with this, its the only thing standing in my way to complete this project.
You don't want to use the working directory at all; you want to use a directory relative to where the web application is located (which can be retrieved from HttpRequest.ApplicationPath.
HttpRequest request = HttpContext.Current.Request;
// get the physical path to the web application
string pathToApp = request.MapPath(request.ApplicationPath);
string usersPath = System.IO.Path.Combine(pathToApp, "Users");
Update
As VincayC points out; asp.net development is not my strongest skill ;) The above code is essentially equivalent of this (much simpler) code:
string usersPath = HttpRequest.Current.Request.MapPath("~/Users");
If this code appears in the code-behind of a page, you can probably cut HttpContext.Current as well, since the page has a Request property.
That did fix the one problem I'm having, but the downloads are still not downloading from the right place, the program still wants to get the files from "C:\Program Files (x86)\Common Files\microsoft shared\DevServer\10.0\" directory here is the code I'm using
--Code to populate the checkbox--
HttpRequest request = HttpContext.Current.Request;
// get the physical path to the web application
string appPath = request.MapPath(request.ApplicationPath);
string directory = System.IO.Path.Combine(appPath, "DownloadLibrary/");
// Get the list of files into the CheckBoxList
var dirInfo = new DirectoryInfo(directory);
cblFiles.DataSource = dirInfo.GetFiles();
cblFiles.DataBind();
--Download Button Code--
// Tell the browser we're sending a ZIP file!
var downloadFileName = string.Format("Items-{0}.zip", DateTime.Now.ToString("yyyy-MM-dd-HH_mm_ss"));
Response.ContentType = "application/zip";
Response.AddHeader("Content-Disposition", "filename=" + downloadFileName);
// Zip the contents of the selected files
using (var zip = new ZipFile())
{
// Add the password protection, if specified
/*if (!string.IsNullOrEmpty(txtZIPPassword.Text))
{
zip.Password = txtZIPPassword.Text;
// 'This encryption is weak! Please see http://cheeso.members.winisp.net/DotNetZipHelp/html/24077057-63cb-ac7e-6be5-697fe9ce37d6.htm for more details
zip.Encryption = EncryptionAlgorithm.WinZipAes128;
}*/
// Construct the contents of the README.txt file that will be included in this ZIP
var readMeMessage = string.Format("Your ZIP file {0} contains the following files:{1}{1}", downloadFileName, Environment.NewLine);
// Add the checked files to the ZIP
foreach (ListItem li in cblFiles.Items)
if (li.Selected)
{
// Record the file that was included in readMeMessage
readMeMessage += string.Concat("\t* ", li.Text, Environment.NewLine);
// Now add the file to the ZIP (use a value of "" as the second parameter to put the files in the "root" folder)
zip.AddFile(li.Value, "Your Files");
}
// Add the README.txt file to the ZIP
//zip.AddEntry("README.txt", readMeMessage, Encoding.ASCII);
// Send the contents of the ZIP back to the output stream
zip.Save(Response.OutputStream);</pre></code>
I'm not sure how to get the downloads to point to my application directory,I tried everything I can think off.