After writing, the file is not modified on Windows Phone 8.0 - c#

During the execution of this script it is not detected any error, but the file isn't modified. Reading works, writing strangely not.
My script for writing:
private void firstLaunch(){
try {
StreamWriter outfile = new StreamWriter("Path/something.txt");
outfile.WriteLine("somethingElse");
outfile.Close();
}
catch (IOException ex){
MessageBox.Show(ex.Message);
}
}
The file already exists and has already been included in the project with visual studio. At the moment it is completely empty.
Could you help me?

You can use something like this:
var res = App.GetResourceStream(new Uri("test.txt", UriKind.Relative));
var txt = new StreamReader(res.Stream).ReadToEnd();
Just make sure that the file has the Build Action set to Content.
If the file is empty, I would recommend creating one in the folder of your app using IsolatedStorage. That way you can check with IsoStoreSpy the contents of your file.

Related

C# Opening a local file

I am trying to make a simple c# program which opens a file in dotnet core 5 using visual studio, however, it transpires that it is looking for the file relative to where the .exe is stored, not my source files. Is there any way I can change this? So that the file can be stored with my source files?
I have tried using Directory.GetCurrentDirectory(), however, this takes me to .exe file, and I need it to open using a relative path rather than the absolute one.
The code is copied and pasted from the Microsoft C# docs here (In the image I have a './' before the filename, I have tried without, it was just something I tried to get it to work.
Code:
using System;
using System.IO;
namespace Test_File_Opening
{
class Program
{
static void Main(string[] args)
{
String line;
try
{
//Pass the file path and file name to the StreamReader constructor
StreamReader sr = new StreamReader("Sample.txt");
//Read the first line of text
line = sr.ReadLine();
//Continue to read until you reach end of file
while (line != null)
{
//write the lie to console window
Console.WriteLine(line);
//Read the next line
line = sr.ReadLine();
}
//close the file
sr.Close();
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Executing finally block.");
}
}
}
}
Exception: Could not find file 'C:\Users\callu\source\repos\Test_File_Opening\Test_File_Opening\bin\Debug\net5.0\Sample.txt'.
Executing finally block.
The running executable has no knowledge of or connection to the original source code files. They may be moved or deleted entirely for all it knows.
Use an absolute path for your file:
var sr = new StreamReader(#"C:\Some\Path\To\Your\File.txt");
I need it to open using a relative path rather than the absolute one.
No you don't. Because there is no universal relative path between a compiled executable and the source code from which it was compiled.
But a comment on the question offers an alternative:
it needs to be able to run on another machine
That's what config files are for... environment-specific settings. (Alternatively, if your plan all along was to distribute the source code for your users to compile and run themselves then they could simply edit it to their file location anyway.)
If you're using the older App.config style settings, add an App.config to your application and put the file path in the appSettings:
<appSettings>
<add key="FilePath" value="C:\Some\Path\To\Your\File.txt"/>
</appSettings>
Then use that setting in the code:
var sr = new StreamReader(System.Configuration.ConfigurationManager.AppSettings["FilePath"]);
Or, if you're using something newer like appsettings.json then there is documentation for that as well. But the principal is still the same.
You could even roll your own way of maintaining application configuration. Hell, you could even skip a config file entirely and provide the file name as a command line argument when running the application. The point is that any given environment would need a way to tell the application where the file is.

How to detect file copying process has finished in C#

I am working on a project that I need to do the following:
I need to rename an image file. (Open an image from folder, and give a name & save it in to same folder)
try
{
string oldFileName = #"path\to\person1.jpg";
string desFileName = #"path\to\person2.jpg";
File.Copy(oldFileName, desFileName, true);
if (File.Exists(oldFileName))
{
File.Delete(#oldFileName);
}
}
catch (Exception ex)
{
}
I did rename the file using above way.
This process copy the old file with new name, but couldn't remove old file
Exception message :
The process cannot access the file 'path\to\person1.jpg' because it is
being used by another process.
How to resolve this? Please suggest any way to detect copying process has complete or not.
Your copy process is definatly complete on if statement becouse your code is sync.
I bet you got this error becouse file is used by another proccess (not your programm). Maby you have paint open or something else.
You should find it out with process monitor or something else. Check this question.

System.IO.File.Copy never overwrites

In my WinForm I would like to copy/overwrite files.
When the destination file does not exist, the file gets created OK. When the file already exists, it never gets overwriten. Path is on my local computer.
There are no exceptions thrown, and I gave full access to "Everyone". Same issue with FileInfo. Only when I delete the file first it gets created!
My Code:
//File.Delete(path + "gauche.png");
try
{
// FileInfo fi = new FileInfo(Path.Combine(path, Num_Gauche.Value + ".png"));
//fi.CopyTo(Path.Combine(path, "gauche.png"), true);
File.Copy(Path.Combine(path, Num_Gauche.Value + ".png"), Path.Combine(path, "gauche.png"), true);
}
catch (Exception ex )
{
Console.WriteLine(ex.Message);
throw;
}
It could be an ownership issue. If the file was created by another user, your process may not be able to overwrite it. Usually like if the file was created by a installer/MSI that you may have issue to overwrite it by another process.
I will just enable that piece of code to delete the file prior to create it if that works.

System.Exception: Shape file not found: [PATH]

When this method is invoked I get the following stack trace when it reaches OpenAsync():
System.Exception: Shape file not found:
C:\Users\Laura\Desktop\shapes\TOTALMAP\OH_Line_6600v_Expired.shp at
RuntimeCoreNet.Interop.HandleException(Boolean retVal) at
RuntimeCoreNet.CoreFeatureSource.FromShapefile(String filename) at
Esri.ArcGISRuntime.Data.ShapefileTable.OpenAsync(String filename)
at ShapeSQLiteGISDemo.MainPage.d__3.MoveNext()
I have a .dbf and .shx file in the same folder with the same name and I've been running Visual Studio in Administrator Mode.
private async void ImportShapes(object sender, RoutedEventArgs e)
{
try
{
//Get path from file picker
var picker = new FileOpenPicker { SuggestedStartLocation = PickerLocationId.Desktop };
picker.FileTypeFilter.Clear();
picker.FileTypeFilter.Add(".shp");
var file = await picker.PickSingleFileAsync();
//convert folder contents to a ShapefileTable
var shapefile = await ShapefileTable.OpenAsync(file.Path);
//save object to database
_DatabaseConnection.Insert(shapefile);
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
//call a method that loads shapes from the database
LoadDatabaseOntoMap();
}
Any help much appreciated.
I believe the problem is that with Store and UWP apps the .shp file has to be moved to a folder in the local storage before the application can open it.
Will set as the accepted answer if this solves the problem.
EDIT: This is indeed the case, because I was choosing a single file with the the file picker I only had access to that one file. To get multiple files I used the folder picker and filtered away any files that weren't useful.
Try using an app like notepad to open the file by pasting in the path:
C:\Users\Laura\Desktop\shapes\TOTALMAP\OH_Line_6600v_Expired.shp
Does the app open the file?
Are there other examples of shape files that do open? Could this file simply be corrupted?

How to embed CHM file in application

Hey everyone,
I just finished up an application I've been working on for a while now. Probably the most complex one I've made to date. Due to this, I figured I'd go and make a help document to provide users with some info on it.
I've created a CHM file, and set up a helpProvider, however now my problem is how to include this and the HHC (Table of contents) file with my application. I feel like it'd be a pain to require the user to copy the two files themselves, so I'm trying to store them as embedded resources, then have the application write these out in the current directory.
Currently, this is the code I'm using:
var data = Properties.Resources.RERHelp;
using (var stream = new FileStream("RERHelp", FileMode.Create))
{
stream.Write(data, 0, data.Count() - 1);
stream.Flush();
}
helpProvider1.HelpNamespace = Directory.GetCurrentDirectory() + "\\RERHelp\\RERHelp.chm";
This works just fine, but it means I'd have to run through this twice, once with data set to Properties.Resources.RERHelp, and once for the Table of Contents file. Is there a better way to do this? Perhaps some way to embed the CHM and HHC files in the application, and access them without writing them to disk? If that isn't possible, which I'm thinking it isn't, is there a better way to go about it than how I am currently?
Thanks for any help!
Best Regards,
Ian
Apps usually use an installer, or zip archive of some sort. Both methods would allow a user to receive the application and the help files, without having to provide them separately.
Under your project properties - Resources, add a file resource ie:textmag.chm. I use filetype Text for the chm's
private void HelpToolStripMenuItem_Click(object sender, EventArgs e)
{
string helpFileName = "";
try
{
helpFileName = System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "Resources") + #"\TextMag.chm";
Help.ShowHelp(this, helpFileName);
}
catch (Exception ex)
{
string xxx = ex.Message;
}
}
Important: in the properties of the chm file under resources, the Build Action must be Content.
Oh, wow. Turns out I didn't need the HHC file as well. I assumed I did because when I'd open the help dialog, it would say that it couldn't find the table of contents.hhc file. I assumed for some reason it needed that in addition to the CHM. I originally just made a method to pass the resources to so as to prevent redundancy, and called that once for the CHM, and once for the HHC, but then I noticed this bit:
data.Count() - 1
I'm not sure why that - 1 was there, the solution I found had it, so I just left it there. When I removed that, the program ran, wrote out that file, and could then read it for the help documentation without the complaint of the missing HHC. All is well. Thanks for the suggestions, everyone!
So a solution is:
1) Copy your chm file to the required project folder
2) In your Visual C# solution explorer add existing item to the project (your chm file).
3) Select the Project menu then project properties.
4) Add existing resource.
5) Add the below code and connect to your help menu item.
private void WORKING_HELP()
{
string filePath = Directory.GetCurrentDirectory() + "\\BlitzHelp.chm";
try
{
//Check if already exists before making
if (!File.Exists(filePath))
{
var data = Properties.Resources.BlitzHelp;
using (var stream = new FileStream("BlitzHelp.chm", FileMode.Create))
{
stream.Write(data, 0, data.Count());
stream.Flush();
}
MessageBox.Show("file made");
}
}
catch
{
//May already be opened
}
Help.ShowHelp(this, filePath);
}

Categories