从Android C#读取Windows PC共享位置上的文本文件可以通过以下步骤实现:
using System;
using System.IO;
using System.Net;
public class Program
{
public static void Main()
{
string sharedFilePath = @"\\WindowsPC\SharedFolder\file.txt";
string username = "WindowsPCUsername";
string password = "WindowsPCPassword";
NetworkCredential credentials = new NetworkCredential(username, password);
using (new NetworkConnection(sharedFilePath, credentials))
{
string fileContent = File.ReadAllText(sharedFilePath);
Console.WriteLine(fileContent);
}
}
}
public class NetworkConnection : IDisposable
{
private readonly string _networkName;
public NetworkConnection(string networkName, NetworkCredential credentials)
{
_networkName = networkName;
var netResource = new NetResource
{
Scope = ResourceScope.GlobalNetwork,
ResourceType = ResourceType.Disk,
DisplayType = ResourceDisplaytype.Share,
RemoteName = networkName
};
var result = WNetAddConnection2(
netResource,
credentials.Password,
credentials.UserName,
0);
if (result != 0)
{
throw new IOException("Failed to connect to shared folder.");
}
}
~NetworkConnection()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
WNetCancelConnection2(_networkName, 0, true);
}
[DllImport("mpr.dll")]
private static extern int WNetAddConnection2(NetResource netResource,
string password, string username, int flags);
[DllImport("mpr.dll")]
private static extern int WNetCancelConnection2(string name, int flags,
bool force);
}
[StructLayout(LayoutKind.Sequential)]
public class NetResource
{
public ResourceScope Scope;
public ResourceType ResourceType;
public ResourceDisplaytype DisplayType;
public int Usage;
public string LocalName;
public string RemoteName;
public string Comment;
public string Provider;
}
public enum ResourceScope : int
{
Connected = 1,
GlobalNetwork,
Remembered,
Recent,
Context
};
public enum ResourceType : int
{
Any = 0,
Disk = 1,
Print = 2,
Reserved = 8,
}
public enum ResourceDisplaytype : int
{
Generic = 0x0,
Domain = 0x01,
Server = 0x02,
Share = 0x03,
File = 0x04,
Group = 0x05,
Network = 0x06,
Root = 0x07,
Shareadmin = 0x08,
Directory = 0x09,
Tree = 0x0a,
Ndscontainer = 0x0b
}
sharedFilePath
替换为实际的共享文件路径,例如\\WindowsPC\SharedFolder\file.txt
。同时,将username
和password
替换为Windows PC上的用户名和密码。需要注意的是,为了访问共享位置,需要在Android应用中添加网络权限。在AndroidManifest.xml文件中添加以下权限:
<uses-permission android:name="android.permission.INTERNET" />
此外,为了在Android应用中使用C#编程语言,可以使用Xamarin开发工具。Xamarin是一种跨平台开发工具,可以使用C#编写Android应用。
领取专属 10元无门槛券
手把手带您无忧上云