Create text file in a given folder - c#

I am developing a windows 8 app using Microsoft visual studio 2013. I needed to store the user entered data in a text file. I have wrote the following code segment to create the file and its working. But the text file is created in C:\Users...... I want to create the text file in a given folder. How can I modify my code to create the file in a folder where I specify.
StorageFile sampleFile;
const string fileName = "Sample.txt";

This is how you can create a file in C temp folder
String folderPath = #"C:/temp";
FileStream fs = new FileStream(folderPath + "\\Samplee.txt",FileMode.OpenOrCreate, FileAccess.Write);

As told before, Universal apps are sandboxed which means you can't write a file in an arbitrary folder.
You should take a look at the File access sample on how to do it.
Also, you should take a look at the ApplicationData which gives you a lot of choices for saving user entered data. Is it temporary, do you want it to be synced, is it a setting? There sure is a property that suits your needs.
edit: from http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.applicationdata.localfolder.aspx this is what you should do
var applicationData = Windows.Storage.ApplicationData.current;
var localFolder = applicationData.localFolder;
// Write data to a file
function writeTimestamp() {
localFolder.createFileAsync("dataFile.txt", Windows.Storage.CreationCollisionOption.replaceExisting)
.then(function (sampleFile) {
var formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");
var timestamp = formatter.format(new Date());
return Windows.Storage.FileIO.writeTextAsync(sampleFile, timestamp);
}).done(function () {
});
}

You need to set the directory where you want to save the file.
Try this
string dirctory = #"D:\Folder Name"; //This is the location where you want to save the file
if (!Directory.Exists(dirctory))
{
Directory.CreateDirectory(dirctory);
}
File.WriteAllText(Path.Combine(dirctory, "Sample.txt"), "Text you want to Insert");

Related

Get image file path from resources

I have an image file day.jpg in Resources folder and I want to access it in the code as string path not as byte[] img
Here's what I have tried.
string dayWallpaper = Assembly.GetExecutingAssembly().Location + #"..\..\Resources\day.jpg";
// Didn't found it
string dayWallpaper = Resource.day;
// Outputs byte[] and gives me an error
Then I tried to convert the byte[] to String didn't work as well
static byte[] SliceMe(byte[]? source, int pos)
{
byte[]? destfoo = new byte[source.Length - pos];
Array.Copy(source, pos, destfoo, 0, destfoo.Length);
return destfoo;
}
static string ByteToPath(path)
{
String file = Encoding.Unicode.GetString(SliceMe(path, 24)).TrimEnd("\0".ToCharArray());
return file
}
Outputs black screen
Later I search for the file
if (File.Exists(dayWallpaper))
{
do stuff
}
else
{
Console.WriteLine("File does not exists");
}
And gives me the else statement.
In the answer you posted to your question, the fact that your relative path works is an "accident" that would fail on any other device deploying your app because without the existence of the source code project the path doesn't exist. One good option is to mark the day.jpg file as Copy to Output Directory at which point most installer bundlers will pick it up and deploy it in your setup.exe, msi etc. If you are specifically using the Visual Studio IDE, you would do it like this:
Now, at runtime, to acquire the path to the copied file:
var srce = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources", "day.jpg");
However, there is more work to be done, because you state that you "want to store the image in a folder in the executable and the user could add more images later on." The present location of the file is not suitable for that purpose, so I would recommend the additional step of creating an AppData entry for the user to store their created content.
// Obtain a folder that "the user could add to later on".
var appData =
Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
typeof(Program).Assembly.GetName().Name
);
Directory.CreateDirectory(appData);
Since you mention wanting to store the day.jpg image in that folder, go ahead and copy it to the AppData location (if not already there from a previous run of your app).
var dest = Path.Combine(appData, "day.jpg");
// Copy the image (if it's not there already) into folder that the user can add to.
if (!File.Exists(dest))
{
File.Copy(
sourceFileName: srce,
destFileName: dest
);
}
Alternatively, you could set the BuildAction to EmbeddedResource and manipulate the file as a byte stream and achieve the same end result.
I managed to do it this way
string resourcePath = Path.GetFullPath(Assembly.GetExecutingAssembly().Location + #"\..\..\..\..\Resources");
string dayWallpaper = resourcePath + #"\day.jpg";

How to delete the last character of a file with C#

Hello I'm beginner with C# and I want to delete the last character of my file to inject JSON objects to this file manually (I know that's not the best way to do that), so I can get the right format I tried with multiple ways like open the file, manipulating the string (deleting the last character) and when I try to replace the text in that same file I have errors like IOException: The process cannot access the file 'file path' because it is being used by another process or System.UnauthorizedAccessException : 'Access to the path 'C:\Users\ASUS\Desktop\Root' is denied.
I'll show you the code :
StoreLogs Log = new StoreLogs()
{
Id = ID,
DateTime = dateT,
TaskName = task,
SrcAddress = srcPath,
DstAddress = path,
FileSize = DirSize(new DirectoryInfo(srcPath)),
DelayTransfer = ts.Milliseconds,
};
// Record JSON data in the variable
string strResultJson = JsonConvert.SerializeObject(Log);
// Show the JSON Data
// Console.WriteLine(strResultJson);
// Write JSON Data in another file
string MyJSON = null;
string strPath = #"C:\Users\ASUS\Desktop\Backup\logs\log.json";
if (File.Exists(strPath))
{
//FileInfo table = new FileInfo(strPath);
//string strTable = table.OpenText().ReadToEnd();
//string erase = strTable.Remove(strTable.LastIndexOf(']'));
//Console.WriteLine(erase);
//StreamReader r1 = new StreamReader(strPath);
//string strTable = r1.OpenText().ReadToEnd();
//string erase = strTable.Remove(strTable.LastIndexOf(']'));
//r1.Close();
using (StreamReader sr = File.OpenText(strPath))
{
string table = sr.ReadToEnd();
string erase = table.Remove(table.LastIndexOf(']'));
sr.Close();
File.WriteAllText(strPath, erase);
}
//MyJSON = "," + strResultJson;
//File.AppendAllText(strPath, MyJSON + "]");
//Console.WriteLine("The file exists.");
}
else if (!File.Exists(strPath))
{
MyJSON = "[" + strResultJson + "]";
File.WriteAllText(strPath, MyJSON);
Console.WriteLine("The file doesn't exists.");
}
else
{
Console.WriteLine("Error");
}
// End
Console.WriteLine("JSON Object generated !");
Console.ReadLine();
And that's the result I want :
[{"Id":"8484","DateTime":"26 novembre 2019 02:33:35 ","TaskName":"dezuhduzhd","SrcAddress":"C:\\Users\\ASUS\\Desktop\\Root","DstAddress":"C:\\Users\\ASUS\\Desktop\\Backup","FileSize":7997832.0,"DelayTransfer":0.0},{"Id":"8484","DateTime":"26 novembre 2019 02:33:35 ","TaskName":"dezuhduzhd","SrcAddress":"C:\\Users\\ASUS\\Desktop\\Root","DstAddress":"C:\\Users\\ASUS\\Desktop\\Backup","FileSize":7997832.0,"DelayTransfer":0.0},{"Id":"8484","DateTime":"26 novembre 2019 02:33:35 ","TaskName":"dezuhduzhd","SrcAddress":"C:\\Users\\ASUS\\Desktop\\Root","DstAddress":"C:\\Users\\ASUS\\Desktop\\Backup","FileSize":7997832.0,"DelayTransfer":0.0}]
Edit :
Thank you all for your advices
Solution:
FileStream fs = new FileStream(strPath, FileMode.Open, FileAccess.ReadWrite);
fs.SetLength(fs.Length - 1);
fs.Close();
In the code example you have posted you are opening a stream to read the file. A using block will dispose the stream after you exit the block. You are trying to write to the file, while the read stream is still accessing it (the read stream still exists). You've basically opened the file, you read from it, and are trying to write back to it while still holding it open. The reason this is a problem is that you are not using the stream to write. So your second, write, process is unable to access the file. I see you are closing the stream prior to write, but I'm willing to bet it's still holding the reference open.
I would try this method:
How to both read and write a file in C#
what it says is the access to the path (C:\Users\ASUS\Desktop\Root) denied for the user who is running the application. for ex: If you are running from Visual studio on user1 windows login then user1 should have appropriate rights to that root folder. If the code is running by itself (exe) then check the access for that user who is invoking that exe.
Based on the errors you posted seems that:
Maybe you're leaving some stream open pointing to the file you want to edit, use the 'using' statement to avoid this (see this link for more info)
You're trying to access a file when you don't have needed permissions (you aren't a system admin or file is read-only), try changing file ubication or setting it to be writeable (see this link for mor info about the UnauthorizedAccessException exception)
Hope this helps you!

How to create file text in "AppData\Roaming" for any user in C#

I'd like save date my app but I'm not knowing if app save for different users, Example if "andy" I can't use ("C:\Users\Game maker\AppData\Roaming") ,So How to create file in "AppData\Roaming\MaxrayStudyApp" for any user .
Computer myComputer = new Computer();
myComputer.FileSystem.WriteAllText(#"C:\Users\Game maker\AppData\Roaming\MaxrayStudy\data.txt","", false);
Almost a duplicate of this one: Environment.SpecialFolder.ApplicationData returns the wrong folder
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
That should get the folder you need then use Path.Combine() to write to a directory in that folder.
var roamingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var filePath = Path.Combine(roamingDirectory, "MaxrayStudy\\data.txt");
I restart my windows and I write this
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
filePath= (filePath+#"\MaxrayStudyApp\data.txt");
string path =Convert.ToString(filePath);
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(filePath,false)){
file.WriteLine(" XP : 0");}

GetTempFileName() and saving to the AppData folder

In the below code, the files are being saved in the debug folder of the project, I want to store the files in the appdata folder under a generic specified folder!
AViewModel vm = DataContext as AViewModel;
var table = vm.FileSelectedItem;
if (table != null)
{
var filename = System.IO.Path.GetTempFileName();
File.WriteAllBytes(table.FileTitle, table.Data);
Process prc = new Process();
prc.StartInfo.FileName = table.FileTitle;
prc.Start();
}
//table.FileTitle is the name of the file stored in the db
// eg:(test1.docx, test2.pdf, test3.txt, test4.xlsx)
//table.Data is public byte[] Data { get; set; } property
// which stores the files coming from the db.
I am looking at GetFolderPath and trying something like this now
System.IO.Path.GetTempFileName(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
Thanks for any replys!
GetTempFileName returns a full path to a file in the user's temp path. You can't use that to create a file within a specific folder.
Given that you want to store within the AppData folder already, perhaps you are after something more like:
var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "YourCompany\\YourProduct\\Output");
var filename = Path.Combine(path, table.FileTitle);
File.WriteAllBytes(filename, table.Data);
Process.Start(filename);
In case you want to create randomly named file under AppData, you can try
Guid.NewGuid().ToString("N")
That'll give you random string with reasonable certainty it is unique. For folder under AppData:
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Guid.NewGuid().ToString("N"));
Note: at least put it into some subfolder, AppData is folder shared with all other apps.

Get file path from inputstream?

I am trying to get the last modified date from a file, but need its path? Could someone please show me how i can get the file path?
[HttpGet]
public string uploadfile(string token, string filenameP, DateTime modDate, HttpPostedFileBase file)
{
MemoryStream target = new MemoryStream();
file.InputStream.CopyTo(target);
byte[] data = target.ToArray();
//ModDate = File.GetLastWriteTimeUtc("Path");
}
You are creating a new file on the server when you upload. The last modified date will be "now" (the time the file is created). There is no way to snoop the user's machine to get this information (which is not part of the file itself). Can't be done with an HTTP form upload.
Now, some file types may contain metadata in the file which may have pertinent information. If you know the file type and it does contain such metadata then you can open the file and have a look.
You just don't. Most (if not all) browsers do not provide this information for security reasons in internet sceanrios.
You can read date by javascript (HTML5) and send it as hidden input field of form.
Something like
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
output.push(f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() );
}
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
http://www.html5rocks.com/en/tutorials/file/dndfiles/

Categories

Resources