एम्बेडेड संसाधन पाठ फ़ाइल कैसे पढ़ें


693

मैं एक एम्बेडेड संसाधन (पाठ फ़ाइल) का उपयोग कैसे करूं StreamReaderऔर इसे स्ट्रिंग के रूप में वापस करूं? मेरी वर्तमान स्क्रिप्ट एक विंडोज फॉर्म और टेक्स्टबॉक्स का उपयोग करती है जो उपयोगकर्ता को पाठ फ़ाइल में पाठ को खोजने और बदलने की अनुमति देता है जो एम्बेडेड नहीं है।

private void button1_Click(object sender, EventArgs e)
{
    StringCollection strValuesToSearch = new StringCollection();
    strValuesToSearch.Add("Apple");
    string stringToReplace;
    stringToReplace = textBox1.Text;

    StreamReader FileReader = new StreamReader(@"C:\MyFile.txt");
    string FileContents;
    FileContents = FileReader.ReadToEnd();
    FileReader.Close();
    foreach (string s in strValuesToSearch)
    {
        if (FileContents.Contains(s))
            FileContents = FileContents.Replace(s, stringToReplace);
    }
    StreamWriter FileWriter = new StreamWriter(@"MyFile.txt");
    FileWriter.Write(FileContents);
    FileWriter.Close();
}

जवाबों:


1195

आप Assembly.GetManifestResourceStreamविधि का उपयोग कर सकते हैं :

  1. निम्नलिखित usings जोड़ें

    using System.IO;
    using System.Reflection;
    
  2. प्रासंगिक फ़ाइल की संपत्ति सेट करें: मान के साथ
    पैरामीटरBuild ActionEmbedded Resource

  3. निम्नलिखित कोड का उपयोग करें

    var assembly = Assembly.GetExecutingAssembly();
    var resourceName = "MyCompany.MyProduct.MyFile.txt";
    
    using (Stream stream = assembly.GetManifestResourceStream(resourceName))
    using (StreamReader reader = new StreamReader(stream))
    {
        string result = reader.ReadToEnd();
    }
    

    resourceNameमें एम्बेडेड संसाधनों में से एक का नाम है assembly। उदाहरण के लिए, यदि आप एक टेक्स्ट फ़ाइल को एम्बेड करते हैं जिसका नाम "MyFile.txt"डिफ़ॉल्ट नाम स्थान के साथ प्रोजेक्ट के रूट में रखा गया है "MyCompany.MyProduct", तो resourceNameहै "MyCompany.MyProduct.MyFile.txt"। आप Assembly.GetManifestResourceNamesविधि का उपयोग करके विधानसभा में सभी संसाधनों की एक सूची प्राप्त कर सकते हैं ।


resourceNameकेवल फ़ाइल नाम से प्राप्त करने के लिए कोई ब्रेनर एस्ट्रुट (नेमस्पेस सामान पास करके):

string resourceName = assembly.GetManifestResourceNames()
  .Single(str => str.EndsWith("YourFileName.txt"));

एक पूर्ण उदाहरण:

public string ReadResource(string name)
{
    // Determine path
    var assembly = Assembly.GetExecutingAssembly();
    string resourcePath = name;
    // Format: "{Namespace}.{Folder}.{filename}.{Extension}"
    if (!name.StartsWith(nameof(SignificantDrawerCompiler)))
    {
        resourcePath = assembly.GetManifestResourceNames()
            .Single(str => str.EndsWith(name));
    }

    using (Stream stream = assembly.GetManifestResourceStream(resourcePath))
    using (StreamReader reader = new StreamReader(stream))
    {
        return reader.ReadToEnd();
    }
}

5
@ Me.Close: Environment.SpecialFolderडेस्कटॉप फ़ोल्डर प्राप्त करने के लिए एक नज़र रखना । आपको यह ध्यान रखने की आवश्यकता है कि संसाधन को परियोजना के भीतर उसके पथ के आधार पर नाम दिया जाएगा, इसलिए इसका नाम बस नहीं हो सकता है file1.txt
एड्रिएनबैंक्स

15
GetManifestResourceStream@Adrian संकेत के रूप में मार्ग के लिए तर्क की आवश्यकता है। अगर यह किसी की मदद करता है, तो वह रास्ता उस तरह है जैसे @SimpleCoder उदाहरण में दिखाता है MyNamespace.Filename.Ext:। मैंने पहले कोशिश की थी, MyNamespace.Resources.Filename.Extलेकिन यह एक अशक्त परिणाम है।
ज्येल्टन

61
यदि आपके पास अपना संसाधन सीधे प्रोजेक्ट रूट में नहीं है, लेकिन कुछ सबफ़ोल्डर में, संसाधन नाम में इस फ़ोल्डर का नाम डालना न भूलें (उदाहरण के लिए "MyProjectNameSpace.MyProjectSubFolder.FileName.FileEnention")
साशा

19
यह कहने के लिए कि संसाधन "बिल्ड एक्शन" को "एंबेडेड रिसोर्स" के रूप में सेट किया जाना है
इलिडन

7
एक महत्वपूर्ण बिंदु यहां नहीं है। यदि आपने अपनी फ़ाइल को विषम वर्णों (मेरे मामले में UTF8) से निपटने के लिए वैकल्पिक एन्कोडिंग प्रकार के रूप में सहेजा है, तो आपको स्ट्रीम पढ़ने पर एक खाली फ़ाइल वापस मिल सकती है। स्ट्रीम रीडर के निर्माण में एन्कोडिंग प्रकार निर्दिष्ट करके इसे ठीक करें:using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
काइनेटिक

140

आप दो अलग-अलग तरीकों का उपयोग करके एक संसाधन के रूप में एक फ़ाइल जोड़ सकते हैं।

फ़ाइल को एक्सेस करने के लिए आवश्यक C # कोड अलग है , जो फ़ाइल को पहली जगह में जोड़ने के लिए इस्तेमाल की गई विधि पर निर्भर करता है।

विधि 1: मौजूदा फ़ाइल जोड़ें, गुण सेट करें Embedded Resource

फ़ाइल को अपने प्रोजेक्ट में जोड़ें, फिर टाइप टू सेट करें Embedded Resource

नोट: यदि आप इस पद्धति का उपयोग करके फ़ाइल जोड़ते हैं, तो आप GetManifestResourceStreamइसे एक्सेस करने के लिए उपयोग कर सकते हैं ( @dtb से उत्तर देखें )।

यहाँ छवि विवरण दर्ज करें

विधि 2: फ़ाइल को इसमें जोड़ें Resources.resx

Resources.resxफ़ाइल खोलें, फ़ाइल को जोड़ने के लिए ड्रॉपडाउन बॉक्स का उपयोग करें, पर सेट Access Modifierकरें public

नोट: यदि आप इस पद्धति का उपयोग करके फ़ाइल जोड़ते हैं, तो आप Properties.Resourcesइसे एक्सेस करने के लिए उपयोग कर सकते हैं ( @Night वाकर से उत्तर देखें )।

यहाँ छवि विवरण दर्ज करें


5
एक तीसरी विधि परियोजना में फ़ाइल को जोड़ने के लिए है, फिर "आउटपुट निर्देशिका में कॉपी करें" को "ट्रू" पर सेट करें। संकलन पर, फ़ाइल को आउटपुट डायर में कॉपी किया जाता है, और आप सामान्य साधनों का उपयोग करके फ़ाइल को पढ़ सकते हैं। उदाहरण: जब आप एक छवि प्रदर्शित करना चाहते हैं तो WPF ऐप में।
कंटैंगो

तो Resourceकुछ भी नहीं है कि आप एक संसाधन के रूप में आइटम बाहर पढ़ने के लिए अनुमति देता है करने के लिए निर्माण कार्रवाई की स्थापना ? आपको EmbeddedResourceकिसी Resources.resxफ़ाइल का उपयोग करना या जोड़ना है ?
मास्लो

3
@ मैस्लो बिल्ड एक्शन को 'रिसोर्स' में सेट करना एक लिंक किया हुआ संसाधन बनाता है, जबकि बिल्ड एक्शन को 'एंबेडेड रिसोर्स' में सेट करना संसाधन को आउटपुट असेंबली में संकलित करता है। Copy लिंक्ड रिसोर्स ’शब्द fancy कंपाइल पर फाइल को आउटपुट डायरेक्टरी में कॉपी’ करने के लिए एक फैंसी शब्द है (आप किसी सामान्य विधि का उपयोग करके रनटाइम में फाइल को पढ़ सकते हैं)। इन दो प्रकारों के बीच के अंतर के बारे में अधिक जानने के लिए , msdn.microsoft.com/en-us/library/7k989cfy(v=vs.90).aspx पर एडिटिंग और एडिटिंग रिसोर्स (विजुअल C #) देखें
कंटैंगो

यदि आप इस तरह से संसाधनों का उपयोग करना चाहते हैं, लेकिन गतिशील रूप से, इसके बजाय: Properties.Resources.Your_resource_name यह लिखें Properties.Resources.ResourceManager.GetObject("Your_resource_name"):।
लकोर

86

मूल रूप से, आप System.Reflectionवर्तमान विधानसभा का संदर्भ प्राप्त करने के लिए उपयोग करते हैं। फिर, आप उपयोग करें GetManifestResourceStream()

उदाहरण, मेरे द्वारा पोस्ट किए गए पृष्ठ से:

नोट : using System.Reflection;यह काम करने के लिए जोड़ने की जरूरत है

   Assembly _assembly;
   StreamReader _textStreamReader;

   try
   {
      _assembly = Assembly.GetExecutingAssembly();
      _textStreamReader = new StreamReader(_assembly.GetManifestResourceStream("MyNamespace.MyTextFile.txt"));
   }
   catch
   {
      MessageBox.Show("Error accessing resources!");
   }

32
+1 namespaceसंसाधन नाम के भाग के रूप में शामिल करने के लिए
किर्क ब्रॉडहर्स्ट

41
var auxList= System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames(); जब आप सटीक संसाधन नाम सीखना चाहते हैं तो यह विधि बहुत उपयोगी हो सकती है। (सवाल स्टैकओवरफ्लो से लिया गया ।.com/questions/ 27757/… )
ऑस्कर फोली

69

विज़ुअल स्टूडियो में आप सीधे प्रोजेक्ट गुणों के संसाधन टैब (इस उदाहरण में "Analytics") के माध्यम से फ़ाइल संसाधन तक पहुंच एम्बेड कर सकते हैं। दृश्य स्टूडियो स्क्रीन शॉट - संसाधन टैब

परिणामी फ़ाइल को तब बाइट सरणी के रूप में एक्सेस किया जा सकता है

byte[] jsonSecrets = GoogleAnalyticsExtractor.Properties.Resources.client_secrets_reporter;

क्या आपको इसे एक स्ट्रीम के रूप में चाहिए, तो ( https://stackoverflow.com/a/4736185/432976 से )

Stream stream = new MemoryStream(jsonSecrets)

11
आप इसे एक टेक्स्ट फ़ाइल के साथ भी उपयोग कर सकते हैं, जिस स्थिति में आपके पास होगा: string jsonSecrets = YourNameSpace.Properties.Resources.YourFileName;
१४:१३ बजे

30

जब आपने फ़ाइल को संसाधनों में जोड़ा है, तो आपको इसके एक्सेस मोडिफायर का चयन करना चाहिए क्योंकि आप सार्वजनिक रूप से निम्नानुसार कुछ बना सकते हैं।

byte[] clistAsByteArray = Properties.Resources.CLIST01;

CLIST01 एम्बेडेड फ़ाइल का नाम है।

वास्तव में आप resource.Designer.cs पर जा सकते हैं और देख सकते हैं कि गेटर का नाम क्या है।


5
क्या आप इसे और अधिक समझा सकते हैं? जब मैं समाधान एक्सप्लोरर में एक फ़ाइल पर राइट-क्लिक करें- और फिर सेट Actionकरने के लिए Incorporated ressource, मेरे पास Access Modifiersगुण पैनल में कोई फ़ील्ड नहीं है । इसके अलावा, मेरे पास कोई Propersites.Resourcesक्लास नहीं है , मुझे The name 'Properties' does not exist in the current contextआपका कोड संकलित करते समय एक त्रुटि मिलती है ।
सुजैन डुपरॉन

2
यह तभी काम करेगा जब आप फ़ाइल को एम्बेड करेंगे Resources.resx, प्रोजेक्ट में फ़ाइलों को एम्बेड करने के विभिन्न तरीकों पर मेरा जवाब देखें।
कंटैंगो

13

उदाहरण के लिए Testfile.sql प्रोजेक्ट मेनू जोड़ना -> गुण -> संसाधन -> मौजूदा फ़ाइल जोड़ें

    string queryFromResourceFile = Properties.Resources.Testfile.ToString();

यहाँ छवि विवरण दर्ज करें


2
यह बाइट लौटाएगा [], पाठ फ़ाइलों के लिए `Encoding.UTF8.GetString (Properties.Resources.Testfile) का उपयोग करें
19-30 को माइक

12

मुझे पता है कि यह एक पुराना धागा है, लेकिन यह मेरे लिए काम कर रहा है:

  1. पाठ फ़ाइल को प्रोजेक्ट संसाधनों में जोड़ें
  2. एंड्रयू हिल द्वारा ऊपर दिखाया गया है, सार्वजनिक रूप से एक्सेस संशोधक सेट करें
  3. इस तरह से पाठ पढ़ें:

    textBox1 = new TextBox();
    textBox1.Text = Properties.Resources.SomeText;

पाठ जो मैंने संसाधनों में जोड़ा है: 'SomeText.txt'


8

आप @ dtb के उत्तर के इस सरलीकृत संस्करण का भी उपयोग कर सकते हैं:

public string GetEmbeddedResource(string ns, string res)
{
    using (var reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(string.Format("{0}.{1}", ns, res))))
    {
        return reader.ReadToEnd();
    }
}

क्या अापको उस बारे में पूर्ण विशवास है? इस लिंक के अनुसार ऐसा लग रहा है जैसे मैं हूँ .... stackoverflow.com/questions/1065168/…
टिमरज़

8

अभी मैंने जो कुछ सीखा है वह यह है कि आपकी फ़ाइल को "" होने की अनुमति नहीं है। (डॉट) फ़ाइल नाम में।

ए "।"  फ़ाइल नाम में अच्छा नहीं है।

Templates.plainEmailBodyTemplate-en.txt -> काम करता है !!!
Templates.plainEmailBodyTemplate.en.txt -> GetManifestResourceStream के माध्यम से काम नहीं करता है)

शायद इसलिए कि फ्रेमवर्क बनाम फाइलनाम से अधिक उलझन में है ...


3
माफ़ करना। ये गलत है। डॉट्स काम करते हैं। (कम से कम यह मेरे लिए काम किया, NET4.5) मुझे नहीं पता कि आपके पास यह बग क्यों था।
फेलिक्स कील

हां वे काम करते हैं लेकिन वे निर्देशिका विभाजक के रूप में कार्य करते हैं। Templates.plainEmailBodyTemplate.en.txt "\ Templates \ plainEmailBodyTemplate \ en.txt" संसाधन के लिए दिखेगा
पीटर Gfader

नहीं, मैंने यह कोशिश की। GetManifestResourceStream फ़ाइल नाम में एक से अधिक डॉट के साथ एम्बेडेड संसाधनों तक पहुँच सकता है। (NET4.5)
फेलिक्स कील

1
मुझे .NET 4.5 में एक ही समस्या थी। नाम में डॉट्स वाली फाइलें संसाधन संग्रह में भी नहीं जोड़ी गईं। मेथड असेंबली.गेटमैनिफेस्ट.ऑर्गेन नेम्स () मेरे लिए खाली सूची देता है। मुझे पता चला है कि समस्या केवल भाषा कोड के साथ थी। ca.abcd.sk.crt को संसाधनों में नहीं जोड़ा गया जबकि ca.abcd.crt को समस्या के बिना जोड़ा गया।
a.farkas2508

1
अभी भी 2020 में सही है। इसके लिए बहुत बहुत धन्यवाद, मैं इसके साथ पागल हो रहा था।
ज़ेर्मेज़

8

आपकी सभी शक्तियों द्वारा संयुक्त रूप से मैं किसी भी विधानसभा और किसी भी नाम स्थान से संसाधनों को सामान्य तरीके से पढ़ने के लिए इस सहायक वर्ग का उपयोग करता हूं।

public class ResourceReader
{
    public static IEnumerable<string> FindEmbededResources<TAssembly>(Func<string, bool> predicate)
    {
        if (predicate == null) throw new ArgumentNullException(nameof(predicate));

        return
            GetEmbededResourceNames<TAssembly>()
                .Where(predicate)
                .Select(name => ReadEmbededResource(typeof(TAssembly), name))
                .Where(x => !string.IsNullOrEmpty(x));
    }

    public static IEnumerable<string> GetEmbededResourceNames<TAssembly>()
    {
        var assembly = Assembly.GetAssembly(typeof(TAssembly));
        return assembly.GetManifestResourceNames();
    }

    public static string ReadEmbededResource<TAssembly, TNamespace>(string name)
    {
        if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));
        return ReadEmbededResource(typeof(TAssembly), typeof(TNamespace), name);
    }

    public static string ReadEmbededResource(Type assemblyType, Type namespaceType, string name)
    {
        if (assemblyType == null) throw new ArgumentNullException(nameof(assemblyType));
        if (namespaceType == null) throw new ArgumentNullException(nameof(namespaceType));
        if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));

        return ReadEmbededResource(assemblyType, $"{namespaceType.Namespace}.{name}");
    }

    public static string ReadEmbededResource(Type assemblyType, string name)
    {
        if (assemblyType == null) throw new ArgumentNullException(nameof(assemblyType));
        if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));

        var assembly = Assembly.GetAssembly(assemblyType);
        using (var resourceStream = assembly.GetManifestResourceStream(name))
        {
            if (resourceStream == null) return null;
            using (var streamReader = new StreamReader(resourceStream))
            {
                return streamReader.ReadToEnd();
            }
        }
    }
}

3
कप्तान ग्रह के लिए एक प्लस: पी
आलोक

4

मैंने एक एम्बेडेड संसाधन पाठ फ़ाइल का उपयोग पढ़ा:

    /// <summary>
    /// Converts to generic list a byte array
    /// </summary>
    /// <param name="content">byte array (embedded resource)</param>
    /// <returns>generic list of strings</returns>
    private List<string> GetLines(byte[] content)
    {
        string s = Encoding.Default.GetString(content, 0, content.Length - 1);
        return new List<string>(s.Split(new[] { Environment.NewLine }, StringSplitOptions.None));
    }

नमूना:

var template = GetLines(Properties.Resources.LasTemplate /* resource name */);

template.ForEach(ln =>
{
    Debug.WriteLine(ln);
});

3

मुझे पता है कि यह पुराना है, लेकिन मैं सिर्फ NETMF (.Net MicroFramework ) के लिए इंगित करना चाहता था , आप आसानी से कर सकते हैं:

string response = Resources.GetString(Resources.StringResources.MyFileName);

चूंकि NETMF नहीं हैGetManifestResourceStream


3

यहां पर पोस्ट किए गए सभी समाधानों को पढ़ने के बाद। यह मैंने इसे कैसे हल किया:

// How to embedded a "Text file" inside of a C# project
//   and read it as a resource from c# code:
//
// (1) Add Text File to Project.  example: 'myfile.txt'
//
// (2) Change Text File Properties:
//      Build-action: EmbeddedResource
//      Logical-name: myfile.txt      
//          (note only 1 dot permitted in filename)
//
// (3) from c# get the string for the entire embedded file as follows:
//
//     string myfile = GetEmbeddedResourceFile("myfile.txt");

public static string GetEmbeddedResourceFile(string filename) {
    var a = System.Reflection.Assembly.GetExecutingAssembly();
    using (var s = a.GetManifestResourceStream(filename))
    using (var r = new System.IO.StreamReader(s))
    {
        string result = r.ReadToEnd();
        return result;
    }
    return "";      
}

3

जवाब काफी सरल है, बस ऐसा करें यदि आपने फ़ाइल को सीधे resource.resx से जोड़ दिया।

string textInResourceFile = fileNameSpace.Properties.Resources.fileName;

कोड की उस पंक्ति के साथ, फ़ाइल से पाठ सीधे फ़ाइल से पढ़ा जाता है और स्ट्रिंग चर में डाल दिया जाता है।


2

मुझे गुस्सा आ रहा था कि आपको हमेशा स्ट्रिंग में नाम स्थान और फ़ोल्डर शामिल करना था। मैं एम्बेडेड संसाधनों तक पहुंच को आसान बनाना चाहता था। यही कारण है कि मैंने यह छोटी कक्षा लिखी। उपयोग और सुधार करने के लिए स्वतंत्र महसूस करें!

उपयोग:

using(Stream stream = EmbeddedResources.ExecutingResources.GetStream("filename.txt"))
{
 //...
}

वर्ग:

public class EmbeddedResources
{
    private static readonly Lazy<EmbeddedResources> _callingResources = new Lazy<EmbeddedResources>(() => new EmbeddedResources(Assembly.GetCallingAssembly()));

    private static readonly Lazy<EmbeddedResources> _entryResources = new Lazy<EmbeddedResources>(() => new EmbeddedResources(Assembly.GetEntryAssembly()));

    private static readonly Lazy<EmbeddedResources> _executingResources = new Lazy<EmbeddedResources>(() => new EmbeddedResources(Assembly.GetExecutingAssembly()));

    private readonly Assembly _assembly;

    private readonly string[] _resources;

    public EmbeddedResources(Assembly assembly)
    {
        _assembly = assembly;
        _resources = assembly.GetManifestResourceNames();
    }

    public static EmbeddedResources CallingResources => _callingResources.Value;

    public static EmbeddedResources EntryResources => _entryResources.Value;

    public static EmbeddedResources ExecutingResources => _executingResources.Value;

    public Stream GetStream(string resName) => _assembly.GetManifestResourceStream(_resources.Single(s => s.Contains(resName)));

}

1
और सुपर सरल समाधान के बारे में क्या: var resName = Assembly.GetManifestResourceNames ()। जहाँ (i => i.EndsWith (fileName))। FirstOrDefault (); यदि आप संपूर्ण निर्देशिकाओं को असेंबली में रखते हैं तो यह काम नहीं करेगा, लेकिन अन्यथा यह केवल एक पंक्ति है;)
हैरी

@ सुनिश्चित करें कि आप ऐसा कर सकते हैं। यह मेरे उत्तर के साथ कैसे संबंधित है? क्या आप गेटस्ट्रीम विधि में सुधार करना चाहते हैं? और फिर आप अस्पष्टता को कैसे संभालते हैं?
फेलिक्स कील

1
सिस्टम का उपयोग कर @Estevez; System.IO का उपयोग कर; System.Linq का उपयोग करना; System.Reflection का उपयोग करना;
फेलिक्स कील

2
जब किसी अन्य प्रोजेक्ट में रखा जाता है तो किसी कारण वर्ग काम नहीं करता है। कॉलिंग और एक्ज़ीक्यूटिंग असेंबली दोनों इस क्लास के साथ असेंबली को संदर्भित करते हैं, न कि वास्तव में परीक्षणों को निष्पादित करने वाले। स्थिर और आलसी प्रारंभ के बिना सभी अच्छे, थो।
कर्ली ब्रेस

1
@CurlyBrace धन्यवाद। आलसी मूल्यांकन इस उत्तर में एक वास्तविक दोष है, क्योंकि कॉलिंग और निष्पादन असेंबली संदर्भ पर निर्भर करती है। उन्हें हर पहुंच पर हल करने की आवश्यकता है।
फेलिक्स कील

2

कुछ VS .NET प्रोजेक्ट प्रकार .NET (.resx) फ़ाइल को ऑटो-जेनरेट नहीं करते हैं। निम्न चरण आपकी परियोजना में एक संसाधन फ़ाइल जोड़ते हैं:

  1. प्रोजेक्ट नोड को राइट-क्लिक करें और संसाधन फ़ाइल में जोड़ें / नया आइटम चुनें, स्क्रॉल करें। नाम बॉक्स में, उदाहरण के लिए एक उपयुक्त नाम चुनें, संसाधन और बटन जोड़ें पर क्लिक करें।
  2. संसाधन फ़ाइल Resources.resx को प्रोजेक्ट में जोड़ा जाता है और समाधान एक्सप्लोरर में नोड के रूप में देखा जा सकता है।
  3. दरअसल, दो फाइलें बनाई जाती हैं, इसमें एक ऑटो-जेनरेटेड C # क्लास Resources.Designer.cs भी है। इसे संपादित न करें, इसे वी.एस. फ़ाइल में एक वर्ग नाम है Resources

अब आप एक संसाधन के रूप में एक पाठ फ़ाइल जोड़ सकते हैं, उदाहरण के लिए एक xml फ़ाइल:

  1. डबल-क्लिक करें Resources.resx। संसाधन जोड़ें> मौजूदा फ़ाइल जोड़ें और उस फ़ाइल को स्क्रॉल करें जिसे आप शामिल करना चाहते हैं। पहुँच संशोधित करने के लिए डिफ़ॉल्ट मान को आंतरिक छोड़ दें।
  2. एक आइकन नए संसाधन आइटम का प्रतिनिधित्व करता है। यदि चयनित है, तो संपत्ति फलक इसके गुणों को दिखाता है। Xml फ़ाइलों के लिए, संपत्ति एन्कोडिंग के तहत यूनिकोड (UTF-8) का चयन करें - डिफ़ॉल्ट स्थानीय कोडपेज के बजाय कोड पृष्ठ 65001। अन्य पाठ फ़ाइलों के लिए इस फ़ाइल के सही एन्कोडिंग का चयन करें, उदाहरण के लिए कोडपेज 1252।
  3. Xml फ़ाइलों की तरह पाठ फ़ाइलों के लिए, वर्ग Resourcesमें एक प्रकार की संपत्ति stringहोती है जिसे सम्मिलित फ़ाइल के नाम पर रखा जाता है। यदि फ़ाइल का नाम उदाहरण के लिए RibbonManifest.xml है, तो संपत्ति का नाम होना चाहिए RibbonManifest। आपको कोड फ़ाइल Resources.Designer.cs में सटीक नाम मिलता है।
  4. उदाहरण के लिए, किसी भी अन्य स्ट्रिंग संपत्ति की तरह स्ट्रिंग संपत्ति का उपयोग करें string xml = Resources.RibbonManifest:। सामान्य रूप है ResourceFileName.IncludedTextFileName। उपयोग न करें ResourceManager.GetStringक्योंकि स्ट्रिंग संपत्ति के गेट-फ़ंक्शन ने पहले से ही किया है।

1
public class AssemblyTextFileReader
{
    private readonly Assembly _assembly;

    public AssemblyTextFileReader(Assembly assembly)
    {
        _assembly = assembly ?? throw new ArgumentNullException(nameof(assembly));
    }

    public async Task<string> ReadFileAsync(string fileName)
    {
        var resourceName = _assembly.GetManifestResourceName(fileName);

        using (var stream = _assembly.GetManifestResourceStream(resourceName))
        {
            using (var reader = new StreamReader(stream))
            {
                return await reader.ReadToEndAsync();
            }
        }
    }
}

public static class AssemblyExtensions
{
    public static string GetManifestResourceName(this Assembly assembly, string fileName)
    {
        string name = assembly.GetManifestResourceNames().SingleOrDefault(n => n.EndsWith(fileName, StringComparison.InvariantCultureIgnoreCase));

        if (string.IsNullOrEmpty(name))
        {
            throw new FileNotFoundException($"Embedded file '{fileName}' could not be found in assembly '{assembly.FullName}'.", fileName);
        }

        return name;
    }
}

0

यह एक वर्ग है जो आपको वर्तमान से एम्बेडेड संसाधन फ़ाइलों को पढ़ने के लिए बहुत सुविधाजनक लग सकता है Assembly:

using System.IO;
using System.Linq;
using System.Text;
using static System.IO.Path;
using static System.Reflection.Assembly;

public static class EmbeddedResourceUtils
{
    public static string ReadFromResourceFile(string endingFileName)
    {
        var assembly = GetExecutingAssembly();
        var manifestResourceNames = assembly.GetManifestResourceNames();

        foreach (var resourceName in manifestResourceNames)
        {
            var fileNameFromResourceName = _GetFileNameFromResourceName(resourceName);
            if (!fileNameFromResourceName.EndsWith(endingFileName))
            {
                continue;
            }

            using (var manifestResourceStream = assembly.GetManifestResourceStream(resourceName))
            {
                if (manifestResourceStream == null)
                {
                    continue;
                }

                using (var streamReader = new StreamReader(manifestResourceStream))
                {
                    return streamReader.ReadToEnd();
                }
            }
        }

        return null;
    }

    // https://stackoverflow.com/a/32176198/3764804
    private static string _GetFileNameFromResourceName(string resourceName)
    {
        var stringBuilder = new StringBuilder();
        var escapeDot = false;
        var haveExtension = false;

        for (var resourceNameIndex = resourceName.Length - 1;
            resourceNameIndex >= 0;
            resourceNameIndex--)
        {
            if (resourceName[resourceNameIndex] == '_')
            {
                escapeDot = true;
                continue;
            }

            if (resourceName[resourceNameIndex] == '.')
            {
                if (!escapeDot)
                {
                    if (haveExtension)
                    {
                        stringBuilder.Append('\\');
                        continue;
                    }

                    haveExtension = true;
                }
            }
            else
            {
                escapeDot = false;
            }

            stringBuilder.Append(resourceName[resourceNameIndex]);
        }

        var fileName = GetDirectoryName(stringBuilder.ToString());
        return fileName == null ? null : new string(fileName.Reverse().ToArray());
    }
}

0

उन सभी लोगों के लिए जो केवल जल्दी से हार्डफॉर्म फ़ाइल के पाठ को विनफॉर्म में चाहते हैं;

  1. समाधान एक्सप्लोरर में अपने एप्लिकेशन को राइट-क्लिक करें> संसाधन> अपनी फ़ाइल जोड़ें।
  2. उस पर क्लिक करें, और गुण टैब में "फ़ाइल टाइप" को "टेक्स्ट" पर सेट करें।
  3. अपने प्रोग्राम में सिर्फ Resources.<name of resource>.toString();फ़ाइल पढ़ने के लिए करें।

मैं इसे सर्वोत्तम अभ्यास या कुछ भी नहीं कहूंगा, लेकिन यह जल्दी से काम करता है और इसे करने की आवश्यकता है।


0

उन उपयोगकर्ताओं के लिए जो VB.Net का उपयोग कर रहे हैं

Imports System.IO
Imports System.Reflection

Dim reader As StreamReader
Dim ass As Assembly = Assembly.GetExecutingAssembly()
Dim sFileName = "MyApplicationName.JavaScript.js" 
Dim reader = New StreamReader(ass.GetManifestResourceStream(sFileName))
Dim sScriptText = reader.ReadToEnd()
reader.Close()

MyApplicationNameमेरे आवेदन का नाम स्थान कहां है यह विधानसभा का नाम नहीं है। यह नाम प्रोजेक्ट की संपत्तियों (एप्लिकेशन टैब) में परिभाषित किया गया है।

यदि आपको सही संसाधन नाम नहीं मिलता है, तो आप GetManifestResourceNames()फ़ंक्शन का उपयोग कर सकते हैं

Dim resourceName() As String = ass.GetManifestResourceNames()

या

Dim sName As String 
    = ass.GetManifestResourceNames()
        .Single(Function(x) x.EndsWith("JavaScript.js"))

या

Dim sNameList 
    = ass.GetManifestResourceNames()
        .Where(Function(x As String) x.EndsWith(".js"))

-1

फॉर्म लोड इवेंट पर एंबेडेड TXT फाइल पढ़ें।

चर को गतिशील रूप से सेट करें।

string f1 = "AppName.File1.Ext";
string f2 = "AppName.File2.Ext";
string f3 = "AppName.File3.Ext";

एक कोशिश कैच को बुलाओ।

try 
{
     IncludeText(f1,f2,f3); 
     /// Pass the Resources Dynamically 
     /// through the call stack.
}

catch (Exception Ex)
{
     MessageBox.Show(Ex.Message);  
     /// Error for if the Stream is Null.
}

शामिल करें के लिए शून्य बनाएँ (), विजुअल स्टूडियो आपके लिए यह करता है। CodeBlock को स्वतःपूर्ण करने के लिए लाइटबल्ब पर क्लिक करें।

उत्पन्न कोड ब्लॉक के अंदर निम्नलिखित रखें

संसाधन 1

var assembly = Assembly.GetExecutingAssembly();
using (Stream stream = assembly.GetManifestResourceStream(file1))
using (StreamReader reader = new StreamReader(stream))
{
string result1 = reader.ReadToEnd();
richTextBox1.AppendText(result1 + Environment.NewLine + Environment.NewLine );
}

संसाधन 2

var assembly = Assembly.GetExecutingAssembly();
using (Stream stream = assembly.GetManifestResourceStream(file2))
using (StreamReader reader = new StreamReader(stream))
{
string result2 = reader.ReadToEnd();
richTextBox1.AppendText(
result2 + Environment.NewLine + 
Environment.NewLine );
}

संसाधन 3

var assembly = Assembly.GetExecutingAssembly();
using (Stream stream = assembly.GetManifestResourceStream(file3))

using (StreamReader reader = new StreamReader(stream))
{
    string result3 = reader.ReadToEnd();
    richTextBox1.AppendText(result3);
}

यदि आप दिए गए चर को कहीं और भेजने की इच्छा रखते हैं, तो बस दूसरे फ़ंक्शन को कॉल करें और ...

using (StreamReader reader = new StreamReader(stream))
{
    string result3 = reader.ReadToEnd();
    ///richTextBox1.AppendText(result3);
    string extVar = result3;

    /// another try catch here.

   try {

   SendVariableToLocation(extVar)
   {
         //// Put Code Here.
   }

       }

  catch (Exception ex)
  {
    Messagebox.Show(ex.Message);
  }

}

यह क्या हासिल किया गया था, एक एकल पाठ बॉक्स के अंदर कई txt फ़ाइलों को संयोजित करने और उनके एम्बेडेड डेटा को पढ़ने का तरीका। जो कोड के इस नमूने के साथ मेरा वांछित प्रभाव था।

हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.