新建一个.NET Core控制台项目,使用文件流读写网络共享盘文件,如下所示:
using System; using System.IO; using System.Text; namespace NetCoreShareFolderReading { class Program { static void Main(string[] args) { string path = @"\192.168.1.150Upload FolderScottDemo.txt"; string text; using (FileStream fs = new FileStream(path, FileMode.Open)) { byte[] data = new byte[fs.Length]; fs.Read(data, 0, data.Length); text = Encoding.ASCII.GetString(data); } Console.WriteLine(text); path = @"\192.168.1.150Upload FolderScott测试文件.txt"; using (StreamReader sr = new StreamReader(path, Encoding.UTF8)) { text = sr.ReadToEnd(); } Console.WriteLine(text); path = @"\192.168.1.150Upload FolderScott测试文件_写回.txt"; using (StreamWriter sw = new StreamWriter(path, false, Encoding.UTF8)) { sw.Write("这是使用C#写入的文件内容,Good day guys~12345678"); } Console.WriteLine("Press any key to end..."); Console.ReadKey(); } } }
可以看到使用文件流读写网络共享盘文件,和读写本地磁盘文件一样。