How to Read/Write Files in .Net Core

How to read/write files in .Net Core?

Package: System.IO.FileSystem

System.IO.File.ReadAllText("MyTextFile.txt"); ?

.NET Core - Multiple read/write operations on a text file

If are using the same code from multiple threads or apps writing to the same file, you may find when one thread is wiring it finds the file already in use.
The only reason for the error message is that the file is not closed.

If the calls to write to the file are sequential from the same app then the file is not getting closed properly.

One way to handle this is to check for locked files and retry later.
something like this can be used to check if the file is open:

public static bool CanBeOpenedForExclusiveRead(string filename)
{
try
{
// Test file for exclusive read/write
using (System.IO.FileStream fileStream = System.IO.File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None))
{
fileStream.Close();
}
return true;
}
catch
{
}

return false;
}

if you are already using something like NLog is to use nlog to "log" writes to a file, where nlog will have better handling of these issues across threads.

Read solution data files ASP.Net Core

I found a simple solution to this.

Firstly, you can create a folder anywhere in your solution, you do not have to stick to the conventions like 'app_data' from .net 4.x.

In my scenario, I created a folder called 'data' at the root of my project, I put my txt file in there and used this code to read the contents to a string array

var owners = System.IO.File.ReadAllLines(@"..\data\Owners.txt");

How to write to a file in .NET Core?

This code is the skeleton I was looking for when I posed the question. It uses only facilities available in .NET Core.

var watcher = new BluetoothLEAdvertisementWatcher();

var logPath = System.IO.Path.GetTempFileName();
var logFile = System.IO.File.Create(logPath);
var logWriter = new System.IO.StreamWriter(logFile);
logWriter.WriteLine("Log message");
logWriter.Dispose();

Read and Uptade txt.file in Asp .Net Core using RichTextEditor

Here is a demo about how to read and upload the txt file:

Firstly,create a txt file in your local computer.

View:

@model Models.Script

@{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<body>
<input type="file" value="import"/>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
@Html.LabelFor(m => m.code)<br/>
@Html.TextAreaFor(m => m.code)
@Html.ValidationMessageFor(m=>m.code,"",new { @class = "error" })
<br/><br/>
<input type="submit" value="Submit" />
<span>@Html.Raw(Model.code)</span>
}
</body>

@section Scripts{
<script src="https://cdn.tiny.cloud/1/7wyujejhpvi3ixga3ss1q5gqwvocaiozzy83w2gvwcd004s4/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script>
<script>
tinymce.init({
selector: 'textarea',
plugins: 'a11ychecker advcode casechange formatpainter linkchecker autolink lists checklist media mediaembed pageembed permanentpen powerpaste table advtable tinycomments tinymcespellchecker',
toolbar: 'a11ycheck addcomment showcomments casechange checklist code formatpainter pageembed permanentpen table',
toolbar_mode: 'floating',
tinycomments_mode: 'embedded',
tinycomments_author: 'Author name',
});
$("input").change(function () {
var fr = new FileReader();
fr.onload = function () {
tinyMCE.activeEditor.setContent(fr.result);
}
fr.readAsText(this.files[0]);
});
</script>
}

Controller:

public class HomeController : Controller
{
public ActionResult Index()
{
var model = new Script()
{
id = 1,
code = "<h1>hello</h1>"
};
return View(model);
}
[HttpPost]
public ActionResult Index(Script script)
{
StreamWriter sw = new StreamWriter("C:\\xxx\\Sample.txt");
//Write a line of text
sw.WriteLine(script.code);
//Close the file
sw.Close();
return View(script);
}
}

Result:
Sample Image

Easiest way to read from and write to files

Use File.ReadAllText and File.WriteAllText.

MSDN example excerpt:

// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);

...

// Open the file to read from.
string readText = File.ReadAllText(path);

Checking if a directory has read and write permissions using .Net Core

FileIOPermission is part of .NET's code security - it's meant to allow you to host .NET code that has lower permissions than the host process (i.e. software process isolation). It doesn't have anything to do with the file system's access rights.

For .NET Core, you can read and modify access control to files with the System.IO.FileSystem.AccessControl package. After adding the package, you can do something like this:

using System.IO;

public void Main(string[] args)
{
var ac = new FileInfo(@"C:\Test.txt").GetAccessControl();

// ac has the ACL for the file
}

Needless to say, this is Windows specific.

File reading and writing inside asp.net web application

Your best bet would be Server.MapPath().

Example:

Put the files inside folder "file" (you can make a folder in your solution, by right clicking your solution and choose add folder)..
then right click the folder..choose existing item , and then choose your files..

To make the path to your files local.. use the follow

Server.MapPath("~\\files\\test.html");

Your code modified

 FileStream file = new FileStream(  Server.MapPath("~\\files\\test.html"), FileMode.Create, FileAccess.Write);


Related Topics



Leave a reply



Submit